package com.shycloud.mido.member.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.constant.SecurityConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.common.pay.alipay.AlipayConfig;
import com.shycloud.mido.common.pay.alipay.bean.AliReturnPayBean;
import com.shycloud.mido.common.pay.alipay.bean.OrderBean;
import com.shycloud.mido.common.pay.alipay.utils.AliH5PayUtil;
import com.shycloud.mido.common.pay.alipay.utils.AliPayUtil;
import com.shycloud.mido.common.pay.iospay.utils.IosPayUtils;
import com.shycloud.mido.common.pay.wxpay.WXPay;
import com.shycloud.mido.common.pay.wxpay.WXUtils.MyConfig;
import com.shycloud.mido.common.pay.wxpay.WXUtils.WXPayNative;
import com.shycloud.mido.common.pay.wxpay.utils.PayCommonUtil;
import com.shycloud.mido.common.pay.wxpay.utils.WxConfigUtil;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.common.sms.sdk.CloopenSmsSDK;
import com.shycloud.mido.common.util.NetworkUtil;
import com.shycloud.mido.common.util.SnowFlakeUtil;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.*;
import com.shycloud.mido.member.api.feign.RemoteOptService;
import com.shycloud.mido.member.api.feign.RemoteOrgService;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.member.api.vo.*;
import com.shycloud.mido.member.config.PayNotifyProperties;
import com.shycloud.mido.member.constants.ShoppingStockConstants;
import com.shycloud.mido.member.mapper.*;
import com.shycloud.mido.member.service.AppShoppingMallService;
import com.shycloud.mido.member.service.MultiAssistService;
import com.shycloud.mido.member.service.OptOrgService;
import com.shycloud.mido.member.service.PayService;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.opter.api.entity.OrgSettledCount;
import com.shycloud.mido.opter.api.entity.StockSaleOrder;
import com.shycloud.mido.organ.api.feign.RemoteOrganService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jdom.JDOMException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

import static com.shycloud.mido.common.pay.wxpay.WXH5Pay.getRandomString;

/**
 * 支付模块实现类
 *
 * @author nianhua.jiang
 * @date 2020/8/7
 */
@Slf4j
@Service
@AllArgsConstructor
public class PayServiceImpl implements PayService {
	
	/** param：rechargeRatioId */
	private static final String PARAM_RECHARGE_RATIO_ID = "rechargeRatioId";
	/** param: vipPackageId */
	private static final String PARAM_VIP_PACKAGE_ID = "vipPackageId";
	/** param：receipt */
	private static final String PARAM_RECEIPT = "receipt";
	/** param：in_app */
	private static final String PARAM_IN_APP = "in_app";
	/** param：transaction_id */
	private static final String PARAM_TRANSACTION_ID = "transaction_id";
	/** param：status */
	private static final String PARAM_STATUS = "status";
	/** IOS 共享密钥 */
	private static final String IOS_SHARE_SECRET = "b9c68f368e544c319bc5cea639db10ae";
	
	/** 信息：快乐贝购买 */
	private static final String BUY_GOLD = "快乐贝购买";
	/** 信息：个月VIP购买 */
	private static final String BUY_VIP = "个月VIP购买";
	
	/** vip会员模块 service */
//	private final VipMemberService vipMemberService;
	/** Organ模块 service */
	private final RemoteOrgService remoteOrgService;
	/** feign 运营商 service */
	private final RemoteOptService remoteOptService;
	///** 活动奖励 service */
	//private final RemoteTaskService remoteTaskService;
	
	/** 支付比例 mapper */
	private final SmRechargeRatioMapper rechargeRatioMapper;
	/** 订单模块 mapper */
	private final MemberOrderMapper memberOrderMapper;
	/** 用户 mapper */
	private final MemberMapper memberMapper;
	/** 充值记录 mapper */
	private final MemberMoneyLogMapper memberMoneyLogMapper;
	/** 金币消费/充值记录 mapper */
	private final MemberGoldLogMapper memberGoldLogMapper;
	/** vip会员价格 mapper */
	private final SmMemberPriceMapper smMemberPriceMapper;
	/** 会员 mapper */
	private final MemberRoleMapper memberRoleMapper;
	/** h5套餐模块 mapper */
	private final BasicProductsComboMapper comboMapper;
	/** 激活码模块 mapper */
	private final MemberActivateMapper memberActivateMapper;
	/** 订单详情 mapper */
	private final MemberOrderDetailMapper orderDetailMapper;
	/** 商品信息 mapper */
	private final BasicGoodsInfoMapper goodsInfoMapper;
	/** 运营商 Mapper */
	private final OptOperatorMapper operatorMapper;
	/** 机构 Mapper */
	private final OrgOrganizationMapper organizationMapper;
	/** 微信小程序直播间业务 mapper */
	private final LiveRoomMapper liveRoomMapper;
	/** 录播间业务 mapper */
	private final RecordRoomMapper recordRoomMapper;
	/** 微信小程序直播间用户业务 mapper */
	private final LiveMemberEnterMapper enterMapper;
	/** 套餐商品关系 Mapper */
	private final BasicComboGoodsMapper comboGoodsMapper;
	/** 订单详情业务 mapper */
	private final MemberOrderDetailMapper memberOrderDetailMapper;
	/** 运营商自定义套餐 mapper */
	private final OptHardwareSaleMapper optHardwareSaleMapper;
	/** redis工具类 */
	private final RedisTemplate<String, String> redisTemplate;
	/** 容联云短信工具类 */
	private final CloopenSmsSDK cloopenSmsSDK;
	/** 分线程 */
	private final PlatformTransactionManager transactionManager;
	/** app商城服务 */
	private final AppShoppingMallService shoppingMallService;
	/** 购物车 mapper */
	private final BasicShoppingCartMapper shoppingCartMapper;
	/** IOS 支付 LOG */
	private final IosPayLogMapper iosPayLogMapper;
	/** 回调地址配置 */
	private final PayNotifyProperties payNotifyProperties;
	/** 开通天天帮 */
	private final MultiAssistService multiAssistService;
	/** 教师模块 mapper */
	private final OrgTeacherDetailedMapper teacherDetailedMapper;
	/** 代理商 feign 模块 */
	private final com.shycloud.mido.opter.api.feign.RemoteOptService optFeignService;
	/** udid 模块 service */
	private final StockDeviceInfoMapper deviceInfoMapper;
	/** 机构模块 feign */
	private final RemoteOrganService orgFeignService;
	/** 签约自动续费业务 mapper */
	private final SmMemberAgreementSignMapper signMapper;
	/** 沙箱环境业务 mapper */
	private final SanboxVipPayMemberMapper sanboxVipPayMemberMapper;
	/** 机构代理商绑定关系 service */
	private final OptOrgService optOrgService;
	
	/**
	 * 支付宝支付虚拟币
	 *
	 * @param map 支付请求参数
	 * @return java.lang.String
	 * @author nianhua.jiang
	 * @date 2020/8/7 9:49
	 */
	@Override
	public Map<String, String> aliPay(Map<String, Integer> map) {
		
		//选择的支付比例ID
		Integer rechargeRatioId = map.get(PARAM_RECHARGE_RATIO_ID);
		//
		Map<String, String> resultMap = MapUtil.newHashMap(2);
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		SmRechargeRatio rechargeRatio = rechargeRatioMapper.selectById(rechargeRatioId);
		//订单价格
		memberOrder.setPrice(rechargeRatio.getMoney());
		//购买虚拟币数量
		memberOrder.setGoldCount(rechargeRatio.getGoldCount());
		//支付类型 1->虚拟币充值
		memberOrder.setOrderType("1");
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		//封装请求数据
		OrderBean orderBean = new OrderBean();
		//支付信息
		orderBean.setSubjecy(BUY_GOLD);
		//支付金额
		orderBean.setTotalAmount(rechargeRatio.getMoney().toString());
		//订单编号
		orderBean.setOutTradeNo(String.valueOf(memberOrder.getOrderNo()));
		
		//支付宝回调地址
		orderBean.setNotifyUrl(payNotifyProperties.getAliNotify());
		resultMap.put("aliReturn", AliPayUtil.alipay(orderBean));
		resultMap.put("orderNo", String.valueOf(memberOrder.getOrderNo()));
		return resultMap;
	}
	
	/**
	 * 支付宝支付教辅权限
	 *
	 * @param map
	 * @return java.util.Map<java.lang.String, java.lang.String>
	 * @author nianhua.jiang
	 * @date 2021/2/9 9:41
	 **/
	@Override
	public Map<String, String> aliPayAssistPermission(Map<String, Object> map) {
		
		//选择开通教辅的ID
		Integer assistId = (Integer) map.get("id");
		//教师ID
		String teacherId = (String) map.get("teacherId");
		//学生ID
		String studentId = (String) map.get("studentId");
		Map<String, String> resultMap = MapUtil.newHashMap(2);
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		BasicGoodsInfo goodsInfo = goodsInfoMapper.selectById(assistId);
		
		//订单价格
		memberOrder.setPrice(goodsInfo.getGoodsPrice());
		//购买商品ID
		memberOrder.setGoodsId(assistId);
		//支付类型 7-> 教辅权限
		memberOrder.setOrderType("7");
		//教师ID
		memberOrder.setTeacherId(teacherId);
		memberOrder.setStudentId(studentId);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		
		//封装请求数据
		OrderBean orderBean = new OrderBean();
		//支付信息
		orderBean.setSubjecy(goodsInfo.getName());
		//支付金额
		orderBean.setTotalAmount(goodsInfo.getGoodsPrice().toString());
		//订单编号
		orderBean.setOutTradeNo(String.valueOf(memberOrder.getOrderNo()));
		
		//支付宝回调地址
		orderBean.setNotifyUrl(payNotifyProperties.getAliNotify());
		resultMap.put("aliReturn", AliPayUtil.alipay(orderBean));
		resultMap.put("orderNo", String.valueOf(memberOrder.getOrderNo()));
		return resultMap;
	}
	
	/**
	 * app 购买在线课时包
	 *
	 * @param map
	 * @return java.util.Map<java.lang.String, java.lang.String>
	 * @author nianhua.jiang
	 * @date 2021/2/23 17:11
	 **/
	@Override
	public Map<String, String> aliPayOnlineCourse(Map<String, Integer> map) {
		
		Integer orgId = map.get("orgId");
		
		Integer goodsId = map.get("goodsId");
		
		Map<String, String> resultMap = MapUtil.newHashMap(2);
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		BasicGoodsInfo goodsInfo = goodsInfoMapper.selectById(goodsId);
		
		//订单价格
		memberOrder.setPrice(goodsInfo.getGoodsPrice());
		//购买商品ID
		memberOrder.setGoodsId(goodsId);
		//支付类型 8-> 在线课课时包
		memberOrder.setOrderType("8");
		//机构ID
		memberOrder.setOrgId(orgId);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		
		//封装请求数据
		OrderBean orderBean = new OrderBean();
		//支付信息
		orderBean.setSubjecy(goodsInfo.getName());
		//支付金额
		orderBean.setTotalAmount(goodsInfo.getGoodsPrice().toString());
		//订单编号
		orderBean.setOutTradeNo(String.valueOf(memberOrder.getOrderNo()));
		
		//支付宝回调地址
		orderBean.setNotifyUrl(payNotifyProperties.getAliNotify());
		resultMap.put("aliReturn", AliPayUtil.alipay(orderBean));
		resultMap.put("orderNo", String.valueOf(memberOrder.getOrderNo()));
		return resultMap;
		
	}
	
	@Override
	public Map<String, String> aliPayHardwareDeposit(Map<String, Object> map) {
		
		//获取商品ID
		Integer goodsId = (Integer) map.get("goodsId");
		//姓名
		String name = (String) map.get("name");
		//手机号/联系方式 必填项，为了追述
		String phone = (String) map.get("phone");
		//邮寄地址
		String address = (String) map.get("address");
		//合作商（机构）ID
		Integer orgId = (Integer) map.get("orgId");
		//订单编号
		String orderNo = (String) map.get("orderNo");
		//身份证号
		String identityCardNo = (String) map.get("identityCardNo");
		MemberOrder memberOrder = new MemberOrder();
		//获取充值金额
		BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(goodsId);
		memberOrder.setOrderNo(Long.valueOf(orderNo));
		//地址 - 存入订单的备注里
		memberOrder.setRemark(address);
		//订单价格
		memberOrder.setPrice(basicGoodsInfo.getGoodsPrice());
		//机构ID
		memberOrder.setOrgId(orgId);
		//支付类型 9 -> 硬件押金
		memberOrder.setOrderType("9");
		//收货人
		memberOrder.setExpressName(name);
		//收货人联系电话
		memberOrder.setExpressPhone(phone);
		//收货人地址
		memberOrder.setExpressAddress(address);
		//商品ID
		memberOrder.setGoodsId(goodsId);
		//身份证号
		memberOrder.setIdentityCardNo(identityCardNo);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		
		OrderBean orderBean = new OrderBean();
		orderBean.setBody("纠错大师租赁押金");
		orderBean.setSubjecy("纠错大师租赁押金");
		orderBean.setTotalAmount(memberOrder.getPrice().toString());
		orderBean.setOutTradeNo(orderNo);
		orderBean.setNotifyUrl(payNotifyProperties.getAliNotify());
		orderBean.setReturnUrl(payNotifyProperties.getPayHardwareDepositReturnUrl() + "?flag=ali@" + orderNo + "@");
		//包装一下结果, 塞入订单号
		Map<String, String> resMap = new HashMap<>();
		resMap.put("form", AliH5PayUtil.alipay(orderBean));
		resMap.put("orderNo", orderNo);
		return resMap;
	}
	
	@SneakyThrows
	@Override
	public Map<String, String> aliPayVip(Map<String, Integer> map) {
		
		//选择的vip套餐ID
		Integer vipPackageId = map.get(PARAM_VIP_PACKAGE_ID);
		//响应体
		Map<String, String> resultMap = MapUtil.newHashMap(3);
		//获取充值比例
		SmMemberPrice memberPrice = smMemberPriceMapper.selectById(vipPackageId);
		
		MemberOrder memberOrder = new MemberOrder();
		//订单价格
		memberOrder.setPrice(memberPrice.getPriceNowRMB());
		//充值月份
		memberOrder.setBuyMonth(memberPrice.getBuyMonths());
		//支付类型 2->VIP支付
		memberOrder.setOrderType("2");
		//赠送打印次数
		memberOrder.setGivePrintCount(memberPrice.getGivePrintCount());
		
		//封装请求数据
		OrderBean orderBean = new OrderBean();
		//支付信息
		orderBean.setSubjecy(memberPrice.getBuyMonths() + BUY_VIP);
		//支付金额
		orderBean.setTotalAmount(memberPrice.getPriceNowRMB().toString());
		//支付宝回调地址
		orderBean.setNotifyUrl(payNotifyProperties.getAliNotify());
		
		// 判断是否是签约服务自动扣款
		if (IosPayUtils.VIP_AUTO_PAY.equals(memberPrice.getIosCode())) {
			
			Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
			long agreementNo = new SnowFlakeUtil(1, machineId).nextId();
			//生成协议单号 - 协议单号为订单号
			log.info("生成商家协议单号为: " + agreementNo);
			//关联的协议号
			memberOrder.setExternalAgreementNo(String.valueOf(agreementNo));
			
			//支付金额 首月优惠
			orderBean.setTotalAmount(memberPrice.getFirstPrice());
			//订单信息记录首月优惠价格
			memberOrder.setPrice(new BigDecimal(memberPrice.getFirstPrice()));
			
			//查询此用户的签约表，取出 agreement_no 字段去 支付宝 校验协议是否有效，若有效则返回错误信息
			List<SmMemberAgreementSign> agreementSigns = signMapper.selectList(new QueryWrapper<SmMemberAgreementSign>().eq("member_id", SecurityUtils.getMember().getId()));
			
			if (agreementSigns.size() != 0) {
				
				List<SmMemberAgreementSign> signingList = agreementSigns.stream().filter(x -> "1".equals(x.getStatus())).collect(Collectors.toList());
				
				//处理未及时关闭的协议，主动查询
				for (SmMemberAgreementSign agreementSign : signingList) {
					boolean resBool = AliPayUtil.agreementQuery(agreementSign.getAgreementNo());
					if (!resBool) {
						//关闭协议
						agreementSign.setStatus("2");
						signMapper.updateById(agreementSign);
					}
				}
				
				if (signingList.size() > 0) {
					throw new BusinessException("您正在自动续费体验期内，无需重复续费, 若您关闭了自动续费，请重新进入此页面重新付款");
				}
				
				//享受一次优惠问题
				if (agreementSigns.stream().anyMatch(x -> "2".equals(x.getStatus()))) {
					orderBean.setTotalAmount(memberPrice.getPriceNowRMB().toString());
					memberOrder.setPrice(memberPrice.getPriceNowRMB());
				}
				
				//用户支付界面关闭【自动续费】问题
				if (agreementSigns.stream().anyMatch(x -> "3".equals(x.getStatus()))) {
					orderBean.setTotalAmount(memberPrice.getPriceNowRMB().toString());
					memberOrder.setPrice(memberPrice.getPriceNowRMB());
				}
				
			}
			
			//保存协议信息
			SmMemberAgreementSign agreementSign = new SmMemberAgreementSign();
			//商家定义的签约订单号
			agreementSign.setExternalAgreementNo(String.valueOf(agreementNo));
			//创建时间
			agreementSign.setCreateTime(LocalDateTime.now());
			//签约类型
			agreementSign.setOrderType("2");
			//状态 未签约
			agreementSign.setStatus("0");
			//用户ID
			agreementSign.setMemberId(SecurityUtils.getMember().getId());
			//下次扣款时间
			agreementSign.setNextPayTime(LocalDate.now());
			if ("MONTH".equals(memberPrice.getAgreementPeriodType())) {
				//时长
				agreementSign.setDuration(memberPrice.getAgreementPeriod() * 30);
			}
			if ("DAY".equals(memberPrice.getAgreementPeriodType())) {
				//时长
				agreementSign.setDuration(memberPrice.getAgreementPeriod());
			}
			signMapper.insert(agreementSign);
			
			//签约参数
			SignParams signParams = new SignParams();
			//个人签约产品码
			signParams.setPersonalProductCode("CYCLE_PAY_AUTH_P");
			//协议签约场景，商户和支付宝签约时确定，商户可咨询技术支持。
			signParams.setSignScene("INDUSTRY|MOBILE");
			//商户签约号，代扣协议中标示用户的唯一签约号
			signParams.setExternalAgreementNo(String.valueOf(agreementNo));
			//用户账号
			Member member = memberMapper.selectById(SecurityUtils.getMember().getId());
			signParams.setExternalLogonId(member.getUsername() + "(" + member.getShowname() + ")");
			//签约信息
			AccessParams accessParams = new AccessParams();
			accessParams.setChannel("ALIPAYAPP");
			signParams.setAccessParams(accessParams);
			//周期管控规则
			PeriodRuleParams periodRuleParams = new PeriodRuleParams();
			//周期类型 period_type 是周期扣款产品必填，枚举值为DAY和MONTH。
			periodRuleParams.setPeriodType(memberPrice.getAgreementPeriodType());
			//周期数period是周期扣款产品必填。与另一参数period_type组合使用确定扣款周期，例如period_type为DAY，period=90，则扣款周期为90天。
			periodRuleParams.setPeriod(Long.valueOf(memberPrice.getAgreementPeriod()));
			//首次执行日期
			if ("MONTH".equals(memberPrice.getAgreementPeriodType())) {
				periodRuleParams.setExecuteTime(LocalDate.now().plusMonths(memberPrice.getAgreementPeriod()).toString());
			}
			if ("DAY".equals(memberPrice.getAgreementPeriodType())) {
				periodRuleParams.setExecuteTime(LocalDate.now().plusDays(memberPrice.getAgreementPeriod()).toString());
			}
			//单次扣款最大金额single_amount是周期扣款产品必填，即每次发起扣款时限制的最大金额，单位为元。商户每次发起扣款都不允许大于此金额。
			periodRuleParams.setSingleAmount(memberPrice.getPriceNowRMB().toString());
			periodRuleParams.setTotalPayments(Long.valueOf(memberPrice.getAgreementTotalPayments()));
			signParams.setPeriodRuleParams(periodRuleParams);
			//签约成功回调地址
			signParams.setSignNotifyUrl(payNotifyProperties.getAliAgreementSignNotify());
			//签约信息（可以为空）
			orderBean.setSignParams(signParams);
			//======== 签约支付 E N D ======================//
		}
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		orderBean.setOutTradeNo(String.valueOf(memberOrder.getOrderNo()));
		resultMap.put("aliReturn", AliPayUtil.alipay(orderBean));
		resultMap.put("orderNo", String.valueOf(memberOrder.getOrderNo()));
		return resultMap;
	}
	
	/**
	 * 支付宝回调（购买虚拟币）
	 *
	 * @param request
	 * @param returnPay
	 * @param response
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public String aliNotify(HttpServletRequest request, AliReturnPayBean returnPay, HttpServletResponse response) {
		
		String payStatus = Constant.ALI_PAYPARAM_TRUE;
		
		try {
			boolean flag = AliPayUtil.returnPay(request, returnPay, response);
			
			if (flag) {
				
				MemberOrder memberOrder = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", returnPay.getOut_trade_no()));
				
				//支付成功
				if (returnPay.getTrade_status().equals(Constant.ALI_PAYPARAM_SUCCESS)) {
					
					//流水号
					memberOrder.setSequenceNumber(returnPay.getTrade_no());
					//订单状态：已支付
					memberOrder.setStatus(Constant.ORDER_STATUS_PAID);
					
					//虚拟币购买
					if ("1".equals(memberOrder.getOrderType())) {
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//充值虚拟币数量
						memberMoneyLog.setGold(memberOrder.getGoldCount());
						//订单编号
						memberMoneyLog.setOrderId(returnPay.getOut_trade_no());
						//支付方式
						memberMoneyLog.setPayMethod("支付宝");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						// sm_member_gold_log 中追加充值金币信息
						MemberGoldLog memberGoldLog = new MemberGoldLog();
						//用户ID
						memberGoldLog.setMemberId(memberOrder.getMemberId());
						//金币变更方式： 1：充值
						memberGoldLog.setType("1");
						//充值金币数量
						memberGoldLog.setGold(memberOrder.getGoldCount());
						//金币充值
						memberGoldLog.setComment("1");
						//创建时间
						memberGoldLog.setCreateTime(LocalDateTime.now());
						//新建
						memberGoldLogMapper.insert(memberGoldLog);
						
						// member表中增加虚拟币余额
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						
						Integer tempGold = member.getGold() + memberOrder.getGoldCount();
						//会员的金币余额
						member.setGold(tempGold);
						
						memberMapper.updateById(member);
					}
					
					if ("2".equals(memberOrder.getOrderType())) {
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//订单编号
						memberMoneyLog.setOrderId(returnPay.getOut_trade_no());
						//支付方式
						memberMoneyLog.setPayMethod("支付宝");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//备注
						memberMoneyLog.setComment("购买VIP" + memberOrder.getBuyMonth() + "个月");
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						//会员充值
						//续费 or 新增会员
						//充值会员
						MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>().eq("member_id", memberOrder.getMemberId()).and(x -> x.eq("role_code", Constant.VIP_MEMBER)));
						
						if (role != null) {
							
							//创建时间
							role.setCreateTime(LocalDateTime.now());
							
							//如果还没到期，那么从到期时间开始累加
							if (role.getEndTime().isAfter(LocalDateTime.now())) {
								role.setEndTime(role.getEndTime().plusMonths(memberOrder.getBuyMonth()));
							}
							//如果已经到期，那么从今天开始累加会员天数
							else {
								role.setStartTime(LocalDateTime.now());
								role.setEndTime(LocalDateTime.now().plusMonths(memberOrder.getBuyMonth()));
							}
							memberRoleMapper.updMemberRole(role);
						} else {
							//新增会员
							role = new MemberRole();
							//创建时间
							role.setCreateTime(LocalDateTime.now());
							//开始时间
							role.setStartTime(LocalDateTime.now());
							//结束时间
							role.setEndTime(LocalDateTime.now().plusMonths(memberOrder.getBuyMonth()));
							//会员
							role.setRoleCode(Constant.VIP_MEMBER);
							//用户ID
							role.setMemberId(memberOrder.getMemberId());
							memberRoleMapper.saveMemberRole(role);
						}
						
						//赠送打印次数
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						member.setPrintAmountGive(memberOrder.getGivePrintCount());
						//判断是否是【自动续费】订单，更新下次【扣款时间】
						if (memberOrder.getExternalAgreementNo() != null) {
							List<SmMemberAgreementSign> agreementSigns = signMapper.selectList(new QueryWrapper<SmMemberAgreementSign>().eq("external_agreement_no", memberOrder.getExternalAgreementNo()));
							for (SmMemberAgreementSign agreementSign : agreementSigns) {
								
								//更新下次扣款时间
								if (agreementSign.getDuration() >= 30) {
									//认为是按月扣费
									agreementSign.setNextPayTime(agreementSign.getNextPayTime().plusMonths(agreementSign.getDuration() / 30));
								} else {
									agreementSign.setNextPayTime(agreementSign.getNextPayTime().plusDays(agreementSign.getDuration()));
								}
								
								if (org.apache.commons.lang3.StringUtils.isEmpty(agreementSign.getAgreementNo())) {
									agreementSign.setStatus("3");
									member.setIsAgreementSign("1");
								}
								signMapper.updateById(agreementSign);
							}
						}
						memberMapper.updateById(member);
					}
					
					if ("3".equals(memberOrder.getOrderType())) {
						//表示是后台商城支付订单
						postProcessMallOrder(memberOrder);
					}
					
					if ("7".equals(memberOrder.getOrderType())) {
						
						BasicGoodsInfo assistGoods = goodsInfoMapper.selectById(memberOrder.getGoodsId());
						
						//总部给教师分配对应时长的天天帮
						MultiAssistRecordVO assistRecordAssign = new MultiAssistRecordVO();
						assistRecordAssign.setSubjectLaunch(Constant.ASSIST_SUBJECT_MASTER);
						assistRecordAssign.setCommonId("38");
						assistRecordAssign.setMemberId("1");
						//工作室
						assistRecordAssign.setSubject(Constant.ASSIST_SUBJECT_TEACHER);
						assistRecordAssign.setTeacherId(memberOrder.getTeacherId());
						//增加
						assistRecordAssign.setType(Constant.ASSIST_TYPE_PLUS);
						//区域开通
						assistRecordAssign.setScope("2");
						assistRecordAssign.setMonthly(assistGoods.getUnitCount());
						
						multiAssistService.assign(assistRecordAssign);
						
						//老师给学生开通
						MultiAssistRecordVO assistRecord = new MultiAssistRecordVO();
						assistRecord.setSubjectLaunch("5");
						assistRecord.setMemberId(memberOrder.getTeacherId());
						assistRecord.setCommonId(memberOrder.getTeacherId());
						
						assistRecord.setSubject("6");
						assistRecord.setStudentId(memberOrder.getStudentId());
						assistRecord.setType("1");//增加
						assistRecord.setScope("1");//区域前台开通
						assistRecord.setMonthly(assistGoods.getUnitCount());
						assistRecord.setOrderNo(memberOrder.getOrderNo());
						
						multiAssistService.opening(assistRecord);
						
						//赠送在线课时长
						//remoteTaskService.receiveAward(9, memberOrder.getMemberId(), memberOrder.getOrgId() + "_" + assistGoods.getUnitCount());
						
					}
					
					if ("8".equals(memberOrder.getOrderType())) {
						
						BasicGoodsInfo goods = goodsInfoMapper.selectById(memberOrder.getGoodsId());
						//机构购买课时
						Integer buyDuration = goods.getUnitCount();
						
						//赠送课时
						Integer giveDuration = 0;
						
						//判断是否有赠送课时
						if (goods.getGiftGoodsId() != null) {
							BasicGoodsInfo giveGoods = goodsInfoMapper.selectById(goods.getGiftGoodsId());
							if (giveGoods == null || "1".equals(giveGoods.getStatus())) {
								giveDuration = 0;
							} else {
								giveDuration = giveGoods.getUnitCount();
							}
						}
						
						OrgOrganization orgOrganization = organizationMapper.selectById(memberOrder.getOrgId());
						//机构剩余课时数量为:原有数量+本次购买获取数量
						orgOrganization.setOnlineCourseAvail(orgOrganization.getOnlineCourseAvail() + buyDuration + giveDuration);
						organizationMapper.updateById(orgOrganization);
						
					}
					
					//用户缴纳押金
					if ("9".equals(memberOrder.getOrderType())) {
						String name = memberOrder.getExpressName();
						String phone = memberOrder.getExpressPhone();
						String address = memberOrder.getExpressAddress();
						//创建出库单，但是不准发货，待合作商交完每年的租金后总部才可以发货，本硬件条归属【合作商】
						createOutSaleOrder(memberOrder.getOrderNo(), memberOrder.getOrgId(), null, name, phone, address);
					}
					//机构微信小程序缴纳服务费
					if ("10".equals(memberOrder.getOrderType())) {
					}
					//机构微信小程序续费服务费
					if ("11".equals(memberOrder.getOrderType())) {
					}
					
				} else {
					//支付失败
					payStatus = Constant.ALI_PAYPARAM_FALSE;
					memberOrder.setStatus(Constant.ORDER_STATUS_PAYFAIL);
				}
				memberOrderMapper.updOrder(memberOrder);
			}
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("阿里支付回调处理异常！");
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("阿里支付回调处理异常！");
		}
		
		return payStatus;
	}
	
	/**
	 * 微信支付
	 *
	 * @param map
	 * @param request
	 * @return com.shycloud.mido.member.api.entity.MemberOrder
	 * @author nianhua.jiang
	 * @date 2020/8/8 15:50
	 */
	@Override
	public Map<String, Map> wxPay(Map<String, Integer> map, HttpServletRequest request) {
		
		//选择的支付比例ID
		Integer rechargeRatioId = map.get(PARAM_RECHARGE_RATIO_ID);
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		SmRechargeRatio rechargeRatio = rechargeRatioMapper.selectById(rechargeRatioId);
		
		//订单价格
		memberOrder.setPrice(rechargeRatio.getMoney());
		//购买虚拟币数量
		memberOrder.setGoldCount(rechargeRatio.getGoldCount());
		//支付类型 1->虚拟币购买
		memberOrder.setOrderType("1");
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		try {
			return WXPay.wxPrePay(WxConfigUtil.APPID, rechargeRatio.getMoney().toString(), "快乐贝购买", payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new BusinessException(e.getMessage());
		}
	}
	
	@Override
	public Map<String, Map> wxPayAssistPermission(Map<String, Object> map, HttpServletRequest request) {
		
		//选择开通教辅的ID
		Integer assistId = (Integer) map.get("id");
		//教师ID
		String teacherId = (String) map.get("teacherId");
		//学生ID
		String studentId = (String) map.get("studentId");
		//机构ID
		Integer orgId = (Integer) map.get("orgId");
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		BasicGoodsInfo goodsInfo = goodsInfoMapper.selectById(assistId);
		
		//订单价格
		memberOrder.setPrice(goodsInfo.getGoodsPrice());
		//购买商品ID
		memberOrder.setGoodsId(assistId);
		//支付类型 7-> 教辅权限
		memberOrder.setOrderType("7");
		//教师ID
		memberOrder.setTeacherId(teacherId);
		//学生ID
		memberOrder.setStudentId(studentId);
		//机构ID
		memberOrder.setOrgId(orgId);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		try {
			return WXPay.wxPrePay(WxConfigUtil.APPID, goodsInfo.getGoodsPrice().toString(), goodsInfo.getName(), payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new BusinessException(e.getMessage());
		}
		
	}
	
	/**
	 * app 在线课时购买
	 *
	 * @param orgId
	 * @param goodsId
	 * @param request
	 * @return java.util.Map<java.lang.String, java.util.Map>
	 * @author nianhua.jiang
	 * @date 2021/2/23 16:46
	 **/
	@Override
	public Map<String, Map> wxPayOnlineCourse(Integer orgId, Integer goodsId, HttpServletRequest request) {
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值比例
		BasicGoodsInfo goodsInfo = goodsInfoMapper.selectById(goodsId);
		
		//订单价格
		memberOrder.setPrice(goodsInfo.getGoodsPrice());
		//购买商品ID
		memberOrder.setGoodsId(goodsId);
		//支付类型 8-> 在线课购买
		memberOrder.setOrderType("8");
		//机构ID
		memberOrder.setOrgId(orgId);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		try {
			return WXPay.wxPrePay(WxConfigUtil.APPID, goodsInfo.getGoodsPrice().toString(), goodsInfo.getName(), payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new BusinessException(e.getMessage());
		}
		
	}
	
	@Override
	public Map<String, Map> wxMiniPay(Map<String, String> map, HttpServletRequest request) {
		
		String roomId = map.get("id");
		String orderType = map.get("type");
		String memberId = map.get("memberId");
		
		//2022/03/12 支付环节增加备注信息 需求地址：https://e.gitee.com/dalian_jiayin/issues/list?issue=I4XJNW
		String remark = map.get("remark");
		//2022/06/08 新增参数 orgId
		Integer orgId = Integer.parseInt(map.get("orgId"));
		//== 支付参数 START ==//
		String price = "";
		String name = "";
		String openId = "";
		String appId = "";
		//== 支付参数 END ==//
		
		MemberOrder memberOrder = new MemberOrder();
		
		memberOrder.setRemark(remark);
		
		if (orderType.equals("5")) {
			LiveRoomEntity room = liveRoomMapper.selectById(roomId);
			price = room.getPrice();
			name = room.getName();
			openId = memberMapper.selectById(memberId).getWxMiniOpenId();
			appId = WxConfigUtil.MINI_APP_ID;
		}
		
		if (orderType.equals("6")) {
			QueryWrapper queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("liveroom_id", roomId);
			RecordRoomEntity recordRoom = recordRoomMapper.selectOne(queryWrapper);
			price = recordRoom.getPrice();
			name = recordRoom.getName();
			openId = memberMapper.selectById(memberId).getWxMiniOpenId();
			appId = WxConfigUtil.MINI_APP_ID;
		}
		
		//机构租赁服务费支付 goodsId = 47 / 续费 goodsId = 49
		if ("10".equals(orderType) || "11".equals(orderType)) {
			//微信的openId
			openId = map.get("openId");
			//关联的押金订单ID
			String relationOrderNo = map.get("relationOrderNo");
			//商品ID
			String goodsId = map.get("goodsId");
			//判断押金订单是否支付
			MemberOrder memberOrderRelation = memberOrderMapper.selectById(relationOrderNo);
			if (memberOrderRelation == null || !"1".equals(memberOrderRelation.getStatus())) {
				throw new BusinessException("用户押金未支付成功，无法缴费");
			}
			//获取商品信息
			BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(goodsId);
			price = basicGoodsInfo.getGoodsPrice().toString();
			name = basicGoodsInfo.getName();
			//关联的押金订单ID
			memberOrder.setRelationOrderNo(Long.parseLong(relationOrderNo));
			appId = WxConfigUtil.MINI_APP_ID_MASTER;
			
			MemberOrder memberOrderPerson = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", relationOrderNo));
			//机构ID
			memberOrder.setOrgId(memberOrderPerson.getOrgId());
			
			//若存在机构预存单数，则优先抵扣预存单数，价格为 0.01 元
			OrgOrganization orgOrganization = organizationMapper.selectById(orgId);
			if (orgOrganization.getPreStorageCount() > 0) {
				price = "0.01";
			}
			
		}
		
		if ("12".equals(orderType)) {
			//微信的openId
			openId = map.get("openId");
			//商品ID
			String goodsId = map.get("goodsId");
			//获取商品信息
			BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(goodsId);
			price = basicGoodsInfo.getGoodsPrice().toString();
			name = basicGoodsInfo.getName();
			appId = WxConfigUtil.MINI_APP_ID_MASTER;
			//机构ID
			memberOrder.setOrgId(orgId);
			memberOrder.setGoodsId(Integer.parseInt(goodsId));
		}
		
		memberOrder.setMemberId(memberId);
		//订单价格
		memberOrder.setPrice(new BigDecimal(price));
		memberOrder.setOrderType(orderType);
		memberOrder.setRoomId(roomId);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		return WXPay.miniPrePay(appId, price, name, openId, payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
	}
	
	@Override
	public Map<String, Map> wxPayVip(Map<String, Integer> map, HttpServletRequest request) {
		
		//选择的vip套餐ID
		Integer vipPackageId = map.get(PARAM_VIP_PACKAGE_ID);
		
		MemberOrder memberOrder = new MemberOrder();
		//获取vip套餐信息
		SmMemberPrice smMemberPrice = smMemberPriceMapper.selectById(vipPackageId);
		
		//订单价格
		memberOrder.setPrice(smMemberPrice.getPriceNowRMB());
		//购买虚拟币数量
		memberOrder.setGoldCount(0);
		//订单类型：VIP购买
		memberOrder.setOrderType("2");
		//购买会员月份
		memberOrder.setBuyMonth(smMemberPrice.getBuyMonths());
		//赠送打印次数
		memberOrder.setGivePrintCount(smMemberPrice.getGivePrintCount());
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		if (IosPayUtils.VIP_AUTO_PAY.equals(smMemberPrice.getIosCode())) {
			return WXPay.contractorder(WxConfigUtil.APPID, smMemberPrice.getPriceNowRMB().toString(), "VIP委托代扣", payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
		}
		
		try {
			return WXPay.wxPrePay(WxConfigUtil.APPID, smMemberPrice.getPriceNowRMB().toString(), "VIP购买", payNotifyProperties.getWxNotify(), String.valueOf(memberOrder.getOrderNo()), request);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new BusinessException(e.getMessage());
		}
	}
	
	/**
	 * 微信回调
	 *
	 * @param request
	 * @param response
	 * @return com.shycloud.mido.member.api.entity.MemberOrder
	 * @author nianhua.jiang
	 * @date 2020/8/8 19:53
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			
			//微信支付操作
			Map<String, String> map = WXPay.wxNotify(request, response);
			//订单信息
			MemberOrder memberOrder = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", map.get(Constant.WX_PAYPARAM_OUT_TRADE_NO)));
			
			//更新订单
			if (Constant.WX_PAYPARAM_SUCCESS.equals(map.get(Constant.WX_PAYPARAM_RETURNCODE))) {
				boolean flag = false;
				
				//流水号
				memberOrder.setSequenceNumber(map.get(Constant.WX_TRANSACTION_ID));
				//订单编号
				memberOrder.setOrderNo(Long.valueOf(map.get(Constant.WX_PAYPARAM_OUT_TRADE_NO)));
				//验签
				if (!memberOrder.getOrderType().equals("3")) {
					flag = WXPay.wxNotify(map, memberOrder.getStatus(), request, response);
				} else {
					flag = true;
				}
				
				if (flag) {
					//订单状态：已支付
					memberOrder.setStatus(Constant.ORDER_STATUS_PAID);
					
					if ("1".equals(memberOrder.getOrderType())) {
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//充值虚拟币数量
						memberMoneyLog.setGold(memberOrder.getGoldCount());
						//订单编号
						memberMoneyLog.setOrderId(map.get(Constant.WX_PAYPARAM_OUT_TRADE_NO));
						//支付方式
						memberMoneyLog.setPayMethod("微信");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						// sm_member_gold_log 中追加充值金币信息
						MemberGoldLog memberGoldLog = new MemberGoldLog();
						//用户ID
						memberGoldLog.setMemberId(memberOrder.getMemberId());
						//金币变更方式： 1：充值
						memberGoldLog.setType("1");
						//充值金币数量
						memberGoldLog.setGold(memberOrder.getGoldCount());
						//金币充值
						memberGoldLog.setComment("1");
						//创建时间
						memberGoldLog.setCreateTime(LocalDateTime.now());
						//新建
						memberGoldLogMapper.insert(memberGoldLog);
						
						// member表中增加虚拟币余额
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						
						Integer tempGold = member.getGold() + memberOrder.getGoldCount();
						//会员的金币余额
						member.setGold(tempGold);
						
						memberMapper.updateById(member);
					}
					
					if ("2".equals(memberOrder.getOrderType())) {
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//订单编号
						memberMoneyLog.setOrderId(map.get(Constant.WX_PAYPARAM_OUT_TRADE_NO));
						//支付方式
						memberMoneyLog.setPayMethod("微信");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//备注
						memberMoneyLog.setComment("购买VIP" + memberOrder.getBuyMonth() + "个月");
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						//会员充值
						//续费 or 新增会员
						//充值会员
						MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>().eq("member_id", memberOrder.getMemberId()).and(x -> x.eq("role_code", Constant.VIP_MEMBER)));
						
						if (role != null) {
							
							//创建时间
							role.setCreateTime(LocalDateTime.now());
							
							//如果还没到期，那么从到期时间开始累加
							if (role.getEndTime().isAfter(LocalDateTime.now())) {
								role.setEndTime(role.getEndTime().plusMonths(memberOrder.getBuyMonth()));
							}
							//如果已经到期，那么从今天开始累加会员天数
							else {
								role.setStartTime(LocalDateTime.now());
								role.setEndTime(LocalDateTime.now().plusMonths(memberOrder.getBuyMonth()));
							}
							memberRoleMapper.updMemberRole(role);
						} else {
							//新增会员
							role = new MemberRole();
							//创建时间
							role.setCreateTime(LocalDateTime.now());
							//开始时间
							role.setStartTime(LocalDateTime.now());
							//结束时间
							role.setEndTime(LocalDateTime.now().plusMonths(memberOrder.getBuyMonth()));
							//会员
							role.setRoleCode(Constant.VIP_MEMBER);
							//用户ID
							role.setMemberId(memberOrder.getMemberId());
							memberRoleMapper.saveMemberRole(role);
						}
						
						//赠送打印次数
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						member.setPrintAmountGive(memberOrder.getGivePrintCount());
						memberMapper.updateById(member);
						
					}
					
					//表示总部后台套餐订单
					if ("3".equals(memberOrder.getOrderType())) {
						postProcessMallOrder(memberOrder);
					}
					
					//H5页面项目套餐购买
					if ("4".equals(memberOrder.getOrderType())) {
					
					}
					
					//直播间付费
					if ("5".equals(memberOrder.getOrderType())) {
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						QueryWrapper<LiveMemberEnterEntity> queryWrapper = new QueryWrapper<>();
						queryWrapper.eq("liveroom_id", memberOrder.getRoomId());
						queryWrapper.eq("member_id", member.getId());
						if (enterMapper.selectList(queryWrapper).size() == 0) {
							LiveMemberEnterEntity enterEntity = new LiveMemberEnterEntity();
							memberOrder.setMemberId(member.getUsername());
							enterEntity.setMemberId(member.getId());
							enterEntity.setLiveroomId(memberOrder.getRoomId());
							enterMapper.insert(enterEntity);
						}
					}
					
					// 录播付费
					if ("6".equals(memberOrder.getOrderType())) {
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						QueryWrapper<LiveMemberEnterEntity> queryWrapper = new QueryWrapper<>();
						queryWrapper.eq("liveroom_id", memberOrder.getRoomId());
						queryWrapper.eq("member_id", member.getId());
						if (enterMapper.selectList(queryWrapper).size() == 0) {
							LiveMemberEnterEntity enterEntity = new LiveMemberEnterEntity();
							memberOrder.setMemberId(member.getUsername());
							enterEntity.setMemberId(member.getId());
							enterEntity.setLiveroomId(memberOrder.getRoomId());
							enterMapper.insert(enterEntity);
						}
					}
					
					if ("7".equals(memberOrder.getOrderType())) {
						
						BasicGoodsInfo assistGoods = goodsInfoMapper.selectById(memberOrder.getGoodsId());
						
						//总部给教师分配对应时长的天天帮
						MultiAssistRecordVO assistRecordAssign = new MultiAssistRecordVO();
						assistRecordAssign.setSubjectLaunch(Constant.ASSIST_SUBJECT_MASTER);
						assistRecordAssign.setCommonId("38");
						assistRecordAssign.setMemberId("1");
						//工作室
						assistRecordAssign.setSubject(Constant.ASSIST_SUBJECT_TEACHER);
						assistRecordAssign.setTeacherId(memberOrder.getTeacherId());
						//增加
						assistRecordAssign.setType(Constant.ASSIST_TYPE_PLUS);
						//区域开通
						assistRecordAssign.setScope("2");
						assistRecordAssign.setMonthly(assistGoods.getUnitCount());
						
						multiAssistService.assign(assistRecordAssign);
						
						//老师给学生开通
						MultiAssistRecordVO assistRecordOpening = new MultiAssistRecordVO();
						assistRecordOpening.setSubjectLaunch("5");
						assistRecordOpening.setMemberId(memberOrder.getTeacherId());
						assistRecordOpening.setCommonId(memberOrder.getTeacherId());
						
						assistRecordOpening.setSubject("6");
						assistRecordOpening.setStudentId(memberOrder.getStudentId());
						//增加
						assistRecordOpening.setType("1");
						// 区域前台开通
						assistRecordOpening.setScope("1");
						assistRecordOpening.setMonthly(assistGoods.getUnitCount());
						assistRecordOpening.setOrderNo(memberOrder.getOrderNo());
						
						multiAssistService.opening(assistRecordOpening);
						
						//赠送在线课时长
						//remoteTaskService.receiveAward(9, memberOrder.getMemberId(), memberOrder.getOrgId() + "_" + assistGoods.getUnitCount());
						
					}
					
					if ("8".equals(memberOrder.getOrderType())) {
						
						BasicGoodsInfo goods = goodsInfoMapper.selectById(memberOrder.getGoodsId());
						//机构购买课时
						Integer buyDuration = goods.getUnitCount();
						
						//赠送课时
						Integer giveDuration = 0;
						
						//判断是否有赠送课时
						if (goods.getGiftGoodsId() != null) {
							BasicGoodsInfo giveGoods = goodsInfoMapper.selectById(goods.getGiftGoodsId());
							if (giveGoods == null || "1".equals(giveGoods.getStatus())) {
								giveDuration = 0;
							} else {
								giveDuration = giveGoods.getUnitCount();
							}
						}
						
						OrgOrganization orgOrganization = organizationMapper.selectById(memberOrder.getOrgId());
						//机构剩余课时数量为:原有数量+本次购买获取数量
						orgOrganization.setOnlineCourseAvail(orgOrganization.getOnlineCourseAvail() + buyDuration + giveDuration);
						organizationMapper.updateById(orgOrganization);
						
					}
					//用户缴纳押金
					if ("9".equals(memberOrder.getOrderType())) {
						String name = memberOrder.getExpressName();
						String phone = memberOrder.getExpressPhone();
						String address = memberOrder.getExpressAddress();
						//创建出库单，但是不准发货，待合作商交完每年的租金后总部才可以发货，本硬件条归属【合作商】
						createOutSaleOrder(memberOrder.getOrderNo(), memberOrder.getOrgId(), null, name, phone, address);
					}
					//机构租赁硬件
					if ("10".equals(memberOrder.getOrderType())) {
						//修改发货状态为【可发货】
						StockSaleOrder stockSaleOrder = memberOrderMapper.getStockSaleByOrderNo(memberOrder.getRelationOrderNo().toString());
						stockSaleOrder.setIsOut("1");
						stockSaleOrder.setComments("机构服务费缴纳完成，可以出库");
						optFeignService.updateStockSaleOrder(stockSaleOrder);
						
						//如果机构存在剩余单数的时候，优先扣除剩余单数
						Integer orgId = memberOrder.getOrgId();
						OrgOrganization orgOrganization = organizationMapper.selectById(orgId);
						
						if (orgOrganization.getPreStorageCount() == 0) {
							R result = orgFeignService.checkAndUpdPreStorageCount(orgId, 1, SecurityConstants.FROM_IN);
							Boolean isCheck = (Boolean) result.getData();
							if (isCheck) {
								orgOrganization.setPreStorageCount(1);
							}
						}
						
						//上级代理商（其实时机构）剩余单数 > 0 时，优先扣除剩余单数，并且不计入【分润未结】数量中，也就是自动结算了。
						if (orgOrganization.getPreStorageCount() > 0) {
							orgFeignService.updPreStorageCount(orgId, -1, SecurityConstants.FROM_IN);
							settledOrder(orgOrganization);
						} else {
							//若剩余单数不足时，匹配此机构是否是代理商本身的机构（org 的 phone = opt 的 phone），若相等，则不计入【分润未结】中
							settledOrderEqualsPhone(orgOrganization);
						}
						
					}
					// 机构续费服务费 与缴费逻辑不通，所以单提出来
					if ("11".equals(memberOrder.getOrderType())) {
						//获取关联的押金订单编号
						Long orderNo = memberOrder.getRelationOrderNo();
						//获取押金订单
						MemberOrder memberOrderRe = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", orderNo));
						memberOrderRe.setRemark("续费成功，日期为：" + LocalDateTime.now().toString());
						memberOrderMapper.updOrder(memberOrderRe);
						
						//获取对应订单的硬件 udid
						StockDeviceInfo stockDeviceInfo = deviceInfoMapper.selectOne(new QueryWrapper<StockDeviceInfo>().eq("order_no", orderNo));
						//目前先固定一年
						orgFeignService.prolongMasterFeign(stockDeviceInfo.getUdid(), 365, SecurityConstants.FROM_IN);
						
						//如果机构存在剩余单数的时候，优先扣除剩余单数
						Integer orgId = memberOrder.getOrgId();
						OrgOrganization orgOrganization = organizationMapper.selectById(orgId);
						
						if (orgOrganization.getPreStorageCount() == 0) {
							R result = orgFeignService.checkAndUpdPreStorageCount(orgId, 1, SecurityConstants.FROM_IN);
							Boolean isCheck = (Boolean) result.getData();
							if (isCheck) {
								orgOrganization.setPreStorageCount(1);
							}
						}
						
						if (orgOrganization.getPreStorageCount() > 0) {
							orgFeignService.updPreStorageCount(orgId, -1, SecurityConstants.FROM_IN);
							settledOrder(orgOrganization);
						} else {
							//若剩余单数不足时，匹配此机构是否是代理商本身的机构（org 的 phone = opt 的 phone），若相等，则不计入【分润未结】中
							settledOrderEqualsPhone(orgOrganization);
						}
					}
					
					if ("12".equals(memberOrder.getOrderType())) {
						Integer orgId = memberOrder.getOrgId();
						BasicGoodsInfo assistGoods = goodsInfoMapper.selectById(memberOrder.getGoodsId());
						orgFeignService.updPreStorageCount(orgId, assistGoods.getUnitCount(), SecurityConstants.FROM_IN);
					}
					
				}
			} else {
				memberOrder.setStatus(Constant.ORDER_STATUS_PAYFAIL);
			}
			memberOrderMapper.updOrder(memberOrder);
			response.getWriter().write(Constant.WX_RETURN_CODE);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("微信支付回调处理异常！");
		} catch (JDOMException e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("微信支付回调处理异常！");
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("微信支付回调处理异常！");
		}
	}
	
	@Override
	public Boolean getIosPayResult(String orderId, String iosCode, String transactionId, String payload) {
		
		log.info("苹果内购校验开始，交易ID：" + transactionId + " base64校验体：" + payload);
		
		//线上环境验证
		String verifyResult = IosPayUtils.buyAppVerify(payload, 1);
		
		if (verifyResult == null) {
			throw new BusinessException("苹果验证失败，返回数据为空");
		} else {
			log.info("线上，苹果平台返回JSON:" + verifyResult);
			JSONObject appleReturn = JSONObject.parseObject(verifyResult);
			String states = appleReturn.getString(PARAM_STATUS);
			//无数据则沙箱环境验证
			if ("21007".equals(states)) {
				verifyResult = IosPayUtils.buyAppVerify(payload, 0);
				log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
				appleReturn = JSONObject.parseObject(verifyResult);
				states = appleReturn.getString(PARAM_STATUS);
			}
			log.info("苹果平台返回值：appleReturn --->" + appleReturn);
			// 前端所提供的收据是有效的验证成功
			if (CommonConstants.STATUS_NORMAL.equals(states)) {
				//返回结果
				JSONObject returnJson = JSONObject.parseObject(appleReturn.getString(PARAM_RECEIPT));
				
				String inApp = returnJson.getString(PARAM_IN_APP);
				List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
				if (!CollectionUtils.isEmpty(inApps)) {
					List<String> transactionIds = new ArrayList<>();
					for (HashMap app : inApps) {
						transactionIds.add((String) app.get(PARAM_TRANSACTION_ID));
					}
					//交易列表包含当前交易，则认为交易成功
					if (transactionIds.contains(transactionId)) {
						
						MemberOrder memberOrder = new MemberOrder();
						//获取充值比例
						SmRechargeRatio rechargeRatio = rechargeRatioMapper.selectOne(new QueryWrapper<SmRechargeRatio>().eq(SmRechargeRatio.COL_IOS_CODE, iosCode));
						//订单价格
						memberOrder.setPrice(rechargeRatio.getMoney());
						//购买虚拟币数量
						memberOrder.setGoldCount(rechargeRatio.getGoldCount());
						//生成会员订单
						createMemberOrder(memberOrder, Constant.PAY_IOS);
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//充值虚拟币数量
						memberMoneyLog.setGold(memberOrder.getGoldCount());
						//订单编号
						memberMoneyLog.setOrderId(String.valueOf(memberOrder.getOrderNo()));
						//支付方式
						memberMoneyLog.setPayMethod("IOS");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						// sm_member_gold_log 中追加充值金币信息
						MemberGoldLog memberGoldLog = new MemberGoldLog();
						//用户ID
						memberGoldLog.setMemberId(memberOrder.getMemberId());
						//金币变更方式： 1：充值
						memberGoldLog.setType("1");
						//充值金币数量
						memberGoldLog.setGold(memberOrder.getGoldCount());
						//金币充值
						memberGoldLog.setComment("1");
						//创建时间
						memberGoldLog.setCreateTime(LocalDateTime.now());
						//新建
						memberGoldLogMapper.insert(memberGoldLog);
						
						// member表中增加虚拟币余额
						Member member = memberMapper.selectById(memberOrder.getMemberId());
						
						Integer tempGold = member.getGold() + memberOrder.getGoldCount();
						//会员的金币余额
						member.setGold(tempGold);
						
						memberMapper.updateById(member);
						
						addIosOrderLog(orderId, iosCode, transactionId, payload, member.getId());
						
						return true;
					}
					throw new BusinessException("当前交易不在交易列表中");
				}
				throw new BusinessException("未能获取获取到交易列表");
			} else {
				throw new BusinessException("支付失败，错误码：" + states);
			}
		}
	}
	
	/**
	 * 购买单本曲集
	 *
	 * @param collectionId
	 * @return java.lang.Boolean
	 * @throws Exception
	 * @author nianhua.jiang
	 * @date 2020/8/10 9:54
	 */
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean payCollection(Integer collectionId) {
		
		//获取曲集价格
		Integer collectionAmount = memberOrderMapper.payCollection(collectionId);
		
		if (collectionAmount == null) {
			throw new BusinessException("该曲集无需购买");
		}

		/*
			//判断是否为会员，若为会员无需购买
			// 是否是会员
			VipMemberVO vipMemberVO = vipMemberService.getVipMemberDetail(SecurityUtils.getMember().getId());
			if ("1".equals(vipMemberVO.getIsVipString())) {
				throw new BusinessException("您已经是会员身份，无需购买曲集");
			}
		*/
		//校验用户账户余额
		Member member = memberMapper.selectById(SecurityUtils.getMember().getId());
		if (member.getGold() < collectionAmount) {
			throw new BusinessException("账户余额不足，请先充值~~");
		}
		
		//校验是否已经购买了该曲集
		Integer isBuy = memberOrderMapper.checkIsByCollection(SecurityUtils.getMember().getId(), collectionId);
		
		if (isBuy > 0) {
			throw new BusinessException("您已经购买过该曲集，无需重复购买");
		}
		
		//购买单本曲集,扣除 member 余额
		Integer amount = member.getGold() - collectionAmount;
		member.setGold(amount);
		memberMapper.updateById(member);
		//记录虚拟币消费信息
		MemberGoldLog smMemberGoldLog = new MemberGoldLog();
		//记录类型：消费
		smMemberGoldLog.setType("0");
		//创建时间
		smMemberGoldLog.setCreateTime(LocalDateTime.now());
		//会员ID
		smMemberGoldLog.setMemberId(SecurityUtils.getMember().getId());
		//虚拟币
		smMemberGoldLog.setGold(collectionAmount);
		//备注
		smMemberGoldLog.setComment("曲集购买，曲集ID为->" + collectionId);
		//新增
		memberGoldLogMapper.insert(smMemberGoldLog);
		
		//追加用户-购买曲集 关系表
		memberOrderMapper.insertMemberBuyCollection(SecurityUtils.getMember().getId(), collectionId, "1", "0");
		
		//创建一个订单
		AppShoppingOrderVO orderVO = new AppShoppingOrderVO();
		List<BasicAppShoppingOrder> shoppingItems = new ArrayList<>();
		BasicAppShoppingOrder shoppingOrder = new BasicAppShoppingOrder();
		shoppingOrder.setCollectionId(collectionId);
		shoppingOrder.setMemberId(member.getId());
		shoppingOrder.setCreateTime(LocalDateTime.now());
		shoppingOrder.setQuantity(1);
		shoppingOrder.setUnitGoldPrice(collectionAmount);
		shoppingItems.add(shoppingOrder);
		orderVO.setShoppingItems(shoppingItems);
		shoppingMallService.createOrder(orderVO);
		
		//如果在购物车中有该曲集，删除
		AppAppShoppingCartVO existingCart = shoppingCartMapper.selectExistingItem(SecurityUtils.getMember().getId(), null, collectionId);
		
		if (existingCart != null) {
			if (existingCart.getCollectionId() != null) {
				shoppingCartMapper.deleteById(existingCart.getId());
			}
		}
		
		return true;
	}
	
	
	/**
	 * ios会员购买
	 *
	 * @param iosCode
	 * @param transactionId
	 * @param payload
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/25 16:09
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean payVipForIos(String orderId, String iosCode, String transactionId, String payload, String originalTransactionId) {
		
		log.info("苹果内购校验开始，交易ID：" + transactionId + "  iosCode:" + iosCode);
		
		String verifyResult = null;
		//线上环境验证
		verifyResult = IosPayUtils.buyAppVerifyAuto(payload, 1, IOS_SHARE_SECRET);
		if (verifyResult == null) {
			throw new BusinessException("苹果验证失败，返回数据为空");
		} else {
			//判断是否是【沙箱环境】
			JSONObject appleReturn = JSONObject.parseObject(verifyResult);
			//无数据则沙箱环境验证
			if ("21007".equals(appleReturn.getString(PARAM_STATUS))) {
				verifyResult = IosPayUtils.buyAppVerifyAuto(payload, 0, IOS_SHARE_SECRET);
				log.info("沙箱环境返回成功！");
			}
			//正式处理的数据返回体
			appleReturn = JSONObject.parseObject(verifyResult);
			log.info("交易ID：" + transactionId + "  苹果平台返回值：appleReturn ---->" + appleReturn);
			// 前端所提供的收据是有效的验证成功
			if (CommonConstants.STATUS_NORMAL.equals(appleReturn.getString(PARAM_STATUS))) {
				//提取 receipt 信息
				JSONObject returnJson = JSONObject.parseObject(appleReturn.getString(PARAM_RECEIPT));
				//提取 in_app 信息
				String inApp = returnJson.getString(PARAM_IN_APP);
				List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
				if (!CollectionUtils.isEmpty(inApps)) {
					
					List<String> transactionIds = new ArrayList<>();
					
					for (HashMap app : inApps) {
						transactionIds.add((String) app.get(PARAM_TRANSACTION_ID));
					}
					
					if (!transactionIds.contains(transactionId)) {
						throw new BusinessException("当前交易不在交易列表中");
					}
					
					//增加判断，是否已经续费成功了
					List<MemberOrder> memberOrders = memberOrderMapper.selectList(new QueryWrapper<MemberOrder>().eq("sequence_number", transactionId));
					
					if (memberOrders.size() > 0) {
						//已经续费成功不给加会员
						return true;
					}
					
					MemberOrder memberOrder = new MemberOrder();
					
					//获取VIP价格
					SmMemberPrice smMemberPrice = smMemberPriceMapper.selectOne(new QueryWrapper<SmMemberPrice>().eq(SmMemberPrice.COL_IOS_CODE, iosCode).eq("version", "2"));
					
					if (smMemberPrice == null) {
						//判断此账号是否是斑马沙盒账号
						String memberId = SecurityUtils.getMember().getId();
						Member member = memberMapper.selectById(memberId);
						Integer count = sanboxVipPayMemberMapper.selectCount(new QueryWrapper<SanboxVipPayMember>().eq("username", member.getUsername()));
						if (count > 0) {
							smMemberPrice = smMemberPriceMapper.selectOne(new QueryWrapper<SmMemberPrice>().eq(SmMemberPrice.COL_IOS_CODE, iosCode).eq("version", "sanBox"));
						}
					}
					
					//TODO 适配首月 1 元价格
					if (IosPayUtils.VIP_AUTO_PAY.equals(iosCode)) {
						//订单价格
						memberOrder.setPrice(smMemberPrice.getPriceNowRMB());
					} else {
						//订单价格
						memberOrder.setPrice(smMemberPrice.getPriceNowRMB());
					}
					
					//订单类型 2-VIP购买
					memberOrder.setOrderType("2");
					//商家订单号
					memberOrder.setSequenceNumber(transactionId);
					//生成会员订单
					createMemberOrder(memberOrder, Constant.PAY_IOS);
					
					// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
					MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
					//交易金额
					memberMoneyLog.setMoney(memberOrder.getPrice());
					//创建时间
					memberMoneyLog.setCreateTime(LocalDateTime.now());
					//充值虚拟币数量
					memberMoneyLog.setGold(0);
					//订单编号
					memberMoneyLog.setOrderId(String.valueOf(memberOrder.getOrderNo()));
					//支付方式
					memberMoneyLog.setPayMethod("IOS");
					//会员ID
					memberMoneyLog.setMemberId(memberOrder.getMemberId());
					//实付金额
					memberMoneyLog.setActualMoney(memberOrder.getPrice());
					//备注
					memberMoneyLog.setComment("购买VIP" + smMemberPrice.getBuyMonths() + "个月");
					//新增操作
					memberMoneyLogMapper.insert(memberMoneyLog);
					
					//充值会员
					MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>().eq("member_id", memberOrder.getMemberId()).and(x -> x.eq("role_code", Constant.VIP_MEMBER)));
					
					if (role != null) {
						
						//创建时间
						role.setCreateTime(LocalDateTime.now());
						
						//如果还没到期，那么从到期时间开始累加
						if (role.getEndTime().isAfter(LocalDateTime.now())) {
							role.setEndTime(role.getEndTime().plusMonths(smMemberPrice.getBuyMonths()));
						}
						//如果已经到期，那么从今天开始累加会员天数
						else {
							role.setStartTime(LocalDateTime.now());
							role.setEndTime(LocalDateTime.now().plusMonths(smMemberPrice.getBuyMonths()));
						}
						memberRoleMapper.updMemberRole(role);
					} else {
						//新增会员
						role = new MemberRole();
						//创建时间
						role.setCreateTime(LocalDateTime.now());
						//开始时间
						role.setStartTime(LocalDateTime.now());
						//结束时间
						role.setEndTime(LocalDateTime.now().plusMonths(smMemberPrice.getBuyMonths()));
						//会员
						role.setRoleCode(Constant.VIP_MEMBER);
						//用户ID
						role.setMemberId(memberOrder.getMemberId());
						memberRoleMapper.saveMemberRole(role);
					}
					
					//赠送打印次数
					Member member = memberMapper.selectById(memberOrder.getMemberId());
					if (IosPayUtils.VIP_AUTO_PAY.equals(iosCode)) {
						member.setIsAgreementSign("1");
					}
					member.setPrintAmountGive(smMemberPrice.getGivePrintCount());
					memberMapper.updateById(member);
					
					return true;
				}
				throw new BusinessException("未能获取获取到交易列表");
			} else {
				throw new BusinessException("支付失败，错误码：" + appleReturn.getString(PARAM_STATUS));
			}
		}
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean payAssistForIos(String orderId, String productId, String transactionId, String payload, String teacherId, String studentId) throws Exception {
		
		log.info("苹果内购校验开始，交易ID：" + transactionId + " base64校验体：" + payload);
		
		//线上环境验证
		String verifyResult = IosPayUtils.buyAppVerify(payload, 1);
		
		if (verifyResult == null) {
			throw new BusinessException("苹果验证失败，返回数据为空");
		} else {
			log.info("线上，苹果平台返回JSON:" + verifyResult);
			JSONObject appleReturn = JSONObject.parseObject(verifyResult);
			String states = appleReturn.getString(PARAM_STATUS);
			//无数据则沙箱环境验证
			if ("21007".equals(states)) {
				verifyResult = IosPayUtils.buyAppVerify(payload, 0);
				log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
				appleReturn = JSONObject.parseObject(verifyResult);
				states = appleReturn.getString(PARAM_STATUS);
			}
			log.info("苹果平台返回值：appleReturn --->" + appleReturn);
			// 前端所提供的收据是有效的验证成功
			if (CommonConstants.STATUS_NORMAL.equals(states)) {
				//返回结果
				JSONObject returnJson = JSONObject.parseObject(appleReturn.getString(PARAM_RECEIPT));
				String inApp = returnJson.getString(PARAM_IN_APP);
				List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
				if (!CollectionUtils.isEmpty(inApps)) {
					List<String> transactionIds = new ArrayList<>();
					for (HashMap app : inApps) {
						transactionIds.add((String) app.get(PARAM_TRANSACTION_ID));
					}
					//交易列表包含当前交易，则认为交易成功，进行购买会员业务逻辑
					if (transactionIds.contains(transactionId)) {
						
						MemberOrder memberOrder = new MemberOrder();
						
						//获取商品详情
						BasicGoodsInfo assistGoods = goodsInfoMapper.selectOne(new QueryWrapper<BasicGoodsInfo>().eq("del_flag", "0").eq("status", "0").eq("ios_code", productId));
						
						//订单价格
						memberOrder.setPrice(assistGoods.getIosPrice());
						//订单类型 7-教辅权限开通
						memberOrder.setOrderType("7");
						memberOrder.setStudentId(studentId);
						
						//机构ID
						OrgTeacherDetailed orgTeacherDetailed = teacherDetailedMapper.selectById(teacherId);
						if (orgTeacherDetailed != null) {
							memberOrder.setOrgId(orgTeacherDetailed.getOrgId());
						}
						//生成会员订单
						createMemberOrder(memberOrder, Constant.PAY_IOS);
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//充值虚拟币数量
						memberMoneyLog.setGold(0);
						//订单编号
						memberMoneyLog.setOrderId(String.valueOf(memberOrder.getOrderNo()));
						//支付方式
						memberMoneyLog.setPayMethod("IOS");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//备注
						memberMoneyLog.setComment(assistGoods.getComment());
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						//总部给教师分配对应时长的天天帮
						MultiAssistRecordVO assistRecordAssign = new MultiAssistRecordVO();
						assistRecordAssign.setSubjectLaunch(Constant.ASSIST_SUBJECT_MASTER);
						assistRecordAssign.setCommonId("38");
						assistRecordAssign.setMemberId("1");
						//工作室
						assistRecordAssign.setSubject(Constant.ASSIST_SUBJECT_TEACHER);
						assistRecordAssign.setTeacherId(teacherId);
						//增加
						assistRecordAssign.setType(Constant.ASSIST_TYPE_PLUS);
						//区域开通
						assistRecordAssign.setScope("2");
						assistRecordAssign.setMonthly(assistGoods.getUnitCount());
						
						multiAssistService.assign(assistRecordAssign);
						
						//老师给学生开通
						MultiAssistRecordVO assistRecord = new MultiAssistRecordVO();
						assistRecord.setSubjectLaunch("5");
						assistRecord.setMemberId(teacherId);
						assistRecord.setCommonId(teacherId);
						
						assistRecord.setSubject("6");
						assistRecord.setStudentId(studentId);
						assistRecord.setType("1");//增加
						assistRecord.setScope("1");//区域前台开通
						assistRecord.setMonthly(assistGoods.getUnitCount());
						assistRecord.setOrderNo(memberOrder.getOrderNo());
						
						multiAssistService.opening(assistRecord);
						
						//赠送在线课时长
						//remoteTaskService.receiveAward(9, memberOrder.getMemberId(), memberOrder.getOrgId() + "_" + assistGoods.getUnitCount());
						
						addIosOrderLog(orderId, productId, transactionId, payload, memberOrder.getMemberId());
						
						return true;
					}
					throw new BusinessException("当前交易不在交易列表中");
				}
				throw new BusinessException("未能获取获取到交易列表");
			} else {
				throw new BusinessException("支付失败，错误码：" + states);
			}
		}
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean payOnlineCourseForIos(String orderId, String productId, String transactionId, String payload, Integer orgId) {
		
		log.info("苹果内购校验开始，交易ID：" + transactionId + " base64校验体：" + payload);
		
		//线上环境验证
		String verifyResult = IosPayUtils.buyAppVerify(payload, 1);
		
		if (verifyResult == null) {
			throw new BusinessException("苹果验证失败，返回数据为空");
		} else {
			log.info("线上，苹果平台返回JSON:" + verifyResult);
			JSONObject appleReturn = JSONObject.parseObject(verifyResult);
			String states = appleReturn.getString(PARAM_STATUS);
			//无数据则沙箱环境验证
			if ("21007".equals(states)) {
				verifyResult = IosPayUtils.buyAppVerify(payload, 0);
				log.info("沙盒环境，苹果平台返回JSON:" + verifyResult);
				appleReturn = JSONObject.parseObject(verifyResult);
				states = appleReturn.getString(PARAM_STATUS);
			}
			log.info("苹果平台返回值：appleReturn --->" + appleReturn);
			// 前端所提供的收据是有效的验证成功
			if (CommonConstants.STATUS_NORMAL.equals(states)) {
				//返回结果
				JSONObject returnJson = JSONObject.parseObject(appleReturn.getString(PARAM_RECEIPT));
				String inApp = returnJson.getString(PARAM_IN_APP);
				List<HashMap> inApps = JSONObject.parseArray(inApp, HashMap.class);
				if (!CollectionUtils.isEmpty(inApps)) {
					List<String> transactionIds = new ArrayList<>();
					for (HashMap app : inApps) {
						transactionIds.add((String) app.get(PARAM_TRANSACTION_ID));
					}
					//交易列表包含当前交易，则认为交易成功，进行购买会员业务逻辑
					if (transactionIds.contains(transactionId)) {
						
						MemberOrder memberOrder = new MemberOrder();
						
						//获取商品详情
						BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(new QueryWrapper<BasicGoodsInfo>().eq("del_flag", "0").eq("status", "0").eq("ios_code", productId));
						
						//订单价格
						memberOrder.setPrice(goodsInfo.getIosPrice());
						//订单类型 8-在线课课时包购买
						memberOrder.setOrderType("8");
						//生成会员订单
						createMemberOrder(memberOrder, Constant.PAY_IOS);
						
						// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
						MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
						//交易金额
						memberMoneyLog.setMoney(memberOrder.getPrice());
						//创建时间
						memberMoneyLog.setCreateTime(LocalDateTime.now());
						//充值虚拟币数量
						memberMoneyLog.setGold(0);
						//订单编号
						memberMoneyLog.setOrderId(String.valueOf(memberOrder.getOrderNo()));
						//支付方式
						memberMoneyLog.setPayMethod("IOS");
						//会员ID
						memberMoneyLog.setMemberId(memberOrder.getMemberId());
						//实付金额
						memberMoneyLog.setActualMoney(memberOrder.getPrice());
						//备注
						memberMoneyLog.setComment(goodsInfo.getComment());
						//新增操作
						memberMoneyLogMapper.insert(memberMoneyLog);
						
						//机构购买课时
						Integer buyDuration = goodsInfo.getUnitCount();
						
						//赠送课时
						Integer giveDuration = 0;
						
						//判断是否有赠送课时
						if (goodsInfo.getGiftGoodsId() != null) {
							BasicGoodsInfo giveGoods = goodsInfoMapper.selectById(goodsInfo.getGiftGoodsId());
							if (giveGoods == null || "1".equals(giveGoods.getStatus())) {
								giveDuration = 0;
							} else {
								giveDuration = giveGoods.getUnitCount();
							}
						}
						
						OrgOrganization orgOrganization = organizationMapper.selectById(orgId);
						//机构剩余课时数量为:原有数量+本次购买获取数量+赠送数量
						orgOrganization.setOnlineCourseAvail(orgOrganization.getOnlineCourseAvail() + buyDuration + giveDuration);
						organizationMapper.updateById(orgOrganization);
						
						addIosOrderLog(orderId, productId, transactionId, payload, memberOrder.getMemberId());
						
						return true;
					}
					throw new BusinessException("当前交易不在交易列表中");
				}
				throw new BusinessException("未能获取获取到交易列表");
			} else {
				throw new BusinessException("支付失败，错误码：" + states);
			}
		}
	}
	
	/**
	 * 生成会员订单
	 *
	 * @param memberOrder
	 * @return com.shycloud.mido.member.api.entity.MemberOrder
	 * @author nianhua.jiang
	 * @date 2020/8/7 9:57
	 */
	private MemberOrder createMemberOrder(MemberOrder memberOrder, String paymentMethod) {
		
		//会员ID
		if (SecurityUtils.getMember() != null) {
			memberOrder.setMemberId(SecurityUtils.getMember().getId());
		}
		
		if (memberOrder.getOrderNo() == null) {
			//雪花算法生成全局唯一orderNo
			Integer machineId = ShoppingStockConstants.getConsistentHash(NetworkUtil.getHostIp());
			long orderNo = new SnowFlakeUtil(1, machineId).nextId();
			log.info("购买生成订单编号为: " + orderNo);
			//订单编号
			memberOrder.setOrderNo(orderNo);
		}
		
		//状态 - 待支付
		if (Constant.PAY_IOS.equals(paymentMethod)) {
			memberOrder.setStatus(Constant.ORDER_STATUS_PAID);
		} else {
			memberOrder.setStatus(Constant.ORDER_STATUS_TOPAY);
		}
		//创建日期
		memberOrder.setCreateTime(LocalDateTime.now());
		//支付方式 1:支付宝 2：微信 3：IOS
		memberOrder.setPaymentMethod(paymentMethod);
		
		//新增订单
		try {
			memberOrderMapper.insert(memberOrder);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("订单已失效，请返回上级界面重新获取订单编号");
		}
		return memberOrder;
	}
	
	/**
	 * H5页面支付套餐项目
	 *
	 * @param map - code,phone,comboId,optId
	 * @return java.util.Map<java.lang.String, java.lang.String>
	 * @author nianhua.jiang
	 * @date 2020/11/18 10:16
	 **/
	@Override
	public Map<String, String> payComboH5(Map<String, Object> map) {
		
		//首先校验验证码
		String code = redisTemplate.opsForValue().get(CommonConstants.DEFAULT_CODE_KEY + "SMS@" + map.get("phone"));
		if (code == null) {
			throw new BusinessException("验证码已过期");
		}
		//校验验证码
		if (!code.equals((String) map.get("code"))) {
			throw new BusinessException("验证码不正确");
		}
		
		//选择的套餐ID
		Integer comboId = (Integer) map.get("comboId");
		
		Map<String, String> resultMap = MapUtil.newHashMap(2);
		MemberOrder memberOrder = new MemberOrder();
		//获取套餐详情
		BasicComboInfo basicComboInfo = comboMapper.selectById(comboId);
		//订单价格
		memberOrder.setPrice(basicComboInfo.getSalePrice());
		//支付类型 4 -> H5页面套餐订单支付
		memberOrder.setOrderType("4");
		//会员ID 存储用户的手机号方便联系用户
		memberOrder.setMemberId((String) map.get("phone"));
		//运营商ID用于给运营商分成
		memberOrder.setOptId((Integer) map.get("optId"));
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_ALI);
		//封装请求数据
		OrderBean orderBean = new OrderBean();
		//显示运营商自定义的套餐名称
		OptHardwareSale optHardwareSale = optHardwareSaleMapper.selectOne(new QueryWrapper<OptHardwareSale>().eq("combo_id", comboId).eq("opt_id", memberOrder.getOptId()));
		
		String comboName = StringUtils.EMPTY;
		if (optHardwareSale != null) {
			comboName = optHardwareSale.getCustomName();
		} else {
			comboName = basicComboInfo.getComboName();
		}
		orderBean.setSubjecy(comboName);
		//支付金额
		orderBean.setTotalAmount(basicComboInfo.getSalePrice().toString());
		//订单编号
		orderBean.setOutTradeNo(String.valueOf(memberOrder.getOrderNo()));
		//orderTest.setReturnUrl("http://192.168.0.127:8081/load");
		orderBean.setReturnUrl("http://shop.joymido.com/load");
		//新增订单内关联套餐详情表
		MemberOrderDetail memberOrderDetail = new MemberOrderDetail();
		//订单编号
		memberOrderDetail.setOrderNo(memberOrder.getOrderNo());
		//套餐ID
		memberOrderDetail.setComboId(basicComboInfo.getId());
		//添加
		memberOrderDetailMapper.insert(memberOrderDetail);
		// 支付宝回调地址
		//orderTest.setNotifyUrl("http://flxp6xpc.xiaomy.net/member/pay/payComboH5Notify");
		orderBean.setNotifyUrl("http://api.joymido.com/member/pay/payComboH5Notify");
		resultMap.put("aliReturn", AliPayUtil.alipayH5(orderBean));
		resultMap.put("orderNo", String.valueOf(memberOrder.getOrderNo()));
		return resultMap;
		
	}
	
	/**
	 * H5页面支付回调 - 由于不是一个应用下的 app 所以不用一个回调方法
	 *
	 * @param request
	 * @param returnPay
	 * @param response
	 * @return void
	 * @author nianhua.jiang
	 * @date 2020/11/18 11:07
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public void payComboH5Notify(HttpServletRequest request, AliReturnPayBean returnPay, HttpServletResponse response) {
		
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);//新发起一个事务
		TransactionStatus status = transactionManager.getTransaction(def);
		
		try {
			boolean flag = AliPayUtil.returnPayH5(request, returnPay, response);
			
			if (flag) {
				
				MemberOrder memberOrder = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", returnPay.getOut_trade_no()));
				
				//支付成功
				if (returnPay.getTrade_status().equals(Constant.ALI_PAYPARAM_SUCCESS)) {
					
					//流水号
					memberOrder.setSequenceNumber(returnPay.getTrade_no());
					//订单状态：已支付
					memberOrder.setStatus(Constant.ORDER_STATUS_PAID);
					
					// 生成套餐激活码
					MemberActivateEntity memberActivateEntity = new MemberActivateEntity();
					// 生成激活码
					String code = "XS" + IdUtil.simpleUUID().substring(0, 8).toUpperCase().replaceAll("0", "B").replaceAll("O", "G");
					while (haveRepeat(code)) {
						code = "XS" + IdUtil.simpleUUID().substring(0, 8).toUpperCase().replaceAll("0", "B").replaceAll("O", "G");
					}
					memberActivateEntity.setActvCode(code);
					//运营商ID
					memberActivateEntity.setOptrId(memberOrder.getOptId());
					
					// 套餐ID
					MemberOrderDetail memberOrderDetail = memberOrderDetailMapper.selectOne(new QueryWrapper<MemberOrderDetail>().eq("order_no", returnPay.getOut_trade_no()));
					//套餐信息
					BasicComboInfo basicComboInfo = comboMapper.selectById(memberOrderDetail.getComboId());
					
					memberActivateEntity.setComboId(memberOrderDetail.getComboId());
					//创建时间
					memberActivateEntity.setCreateTime(LocalDateTime.now());
					//后台分配的套餐类型激活码
					memberActivateEntity.setSpecialType(2);
					//扩展字段，用来存放订单编号
					memberActivateEntity.setExtension(returnPay.getOut_trade_no());
					//激活时长
					memberActivateEntity.setDuration(basicComboInfo.getHardwareDuration());
					//新增套餐类型激活码
					memberActivateMapper.insert(memberActivateEntity);
					
					//查询运营商自定义套餐信息
					OptHardwareSale optHardwareSale = optHardwareSaleMapper.selectOne(new QueryWrapper<OptHardwareSale>().eq("combo_id", memberOrderDetail.getComboId()).eq("opt_id", memberOrder.getOptId()));
					
					String comboName = StringUtils.EMPTY;
					if (optHardwareSale != null) {
						comboName = optHardwareSale.getCustomName();
					} else {
						comboName = basicComboInfo.getComboName();
					}
					
					try {
						memberOrderMapper.updOrder(memberOrder);
					} catch (Exception e) {
						transactionManager.rollback(status);
					}
					
					transactionManager.commit(status);
					
					//发送套餐成功短信
					this.cloopenSmsSDK.sendTemplateSMS(memberOrder.getMemberId(), "793716", new String[]{code}).get("statusCode").toString();
					OptOperator optOperator = operatorMapper.selectById(memberOrder.getOptId());
					
					if (StringUtils.isNotEmpty(optOperator.getAlipay()) || StringUtils.isNotEmpty(optOperator.getAlipayName())) {
						String finalComboName = comboName;
						new Runnable() {
							
							private CloopenSmsSDK cloopenSmsSDK;
							
							@Override
							public void run() {
								try {
									//先将订单状态更新，然后等待11S
									Thread.sleep(11000);
									//执行分账
									if (AliPayUtil.aliRelationSettle(optOperator.getAlipay(), returnPay.getOut_trade_no(), returnPay.getTrade_no(), basicComboInfo.getBonus(), finalComboName + "分账")) {
										System.out.println("分账成功");
									} else {
										memberOrder.setStatus(Constant.ORDER_STATUS_ROYALTY_FAIL);
										memberOrderMapper.updOrder(memberOrder);
										//发送短信告知分账失败
										this.cloopenSmsSDK.sendTemplateSMS(optOperator.getPhone(), "793717", null).get("statusCode").toString();
										throw new BusinessException("分账失败");
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}.run();
					}
				} else {
					System.out.println("回调失败");
					memberOrder.setStatus(Constant.ORDER_STATUS_PAYFAIL);
				}
				
			}
		} catch (BusinessException e) {
			log.error(e.getMessage(), e);
			throw e;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new BusinessException("阿里支付回调处理异常！");
		}
	}
	
	@Override
	public Map<String, String> getComboH5Result(String orderNo) {
		
		try {
			Long i = Long.parseLong(orderNo);
		} catch (Exception e) {
			return null;
		}
		
		//if (!StringUtils.isNumeric(orderNo)) {
		//	return null;
		//}
		
		//查询订单状态
		MemberOrder memberOrder = memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().eq("order_no", orderNo));
		
		Map<String, String> resultMap = MapUtil.newHashMap();
		
		resultMap.put("status", memberOrder.getStatus());
		
		//支付成功
		if ("1".equals(memberOrder.getStatus())) {
			MemberActivateEntity memberActivateEntity = memberActivateMapper.selectOne(new QueryWrapper<MemberActivateEntity>().eq("extension", orderNo));
			resultMap.put("actvCode", memberActivateEntity.getActvCode());
		}
		return resultMap;
	}
	
	@Override
	public Map<String, String> wxWebPrePay(HttpServletRequest request, String outTradeNo, BigDecimal payTotal) {
		Map<String, String> resp = null;
		
		try {
			resp = new HashMap<>();
			Integer price100 = 0;
			MyConfig config = new MyConfig();
			
			if (payTotal != null) {
				price100 = payTotal.multiply(new BigDecimal(100)).intValue();
			} else {
				//			return new R<>(resp.get("err_code"),"二位码生成失败，请联系管理员");
				log.error(resp.get("err_code"));
				log.error("二位码生成失败，请联系管理员");
			}
			//回调地址：微信返回参数时用到
//			String notifyUrl = Constant.WX_NOTIFY_URL;
			String notifyUrl = Constant.WX_NOTIFY_URL_TEST;
			String random1 = getRandomString(32);
			WXPayNative wxpay = new WXPayNative(config);
			Map<String, String> data = new HashMap<String, String>();
			
			data.put("body", "快乐斑马后台商城订单");
			data.put("out_trade_no", outTradeNo);
			data.put("device_info", "WEB");
			data.put("fee_type", "CNY");
			//total_fee金额单位是分
			data.put("total_fee", String.valueOf(price100));
			data.put("spbill_create_ip", PayCommonUtil.getIPAddress(request));
			data.put("notify_url", notifyUrl);
			// 此处指定为扫码支付
			data.put("trade_type", "NATIVE");
			data.put("product_id", random1);
			try {
				resp = wxpay.unifiedOrder(data);
				log.info(JSONObject.toJSONString(resp));
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				log.error(resp.get("err_code"));
				log.error("二位码生成失败，请联系管理员");
			}
			if ("FAIL".equals(resp.get("result_code"))) {
				log.error(resp.get("err_code"));
				log.error("二位码生成失败，请联系管理员");
			} else {
				//			orgOrderService.advanceOrder(dto);
				log.info("生成二维码URL: " + resp.get("code_url"));
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		
		return resp;
	}
	
	@Override
	public Map<String, String> alipayWebPrePay(String outTradeNo, BigDecimal payTotal) {
		AlipayTradePrecreateResponse response = null;
		
		try {
			AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
			
			AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
			
			request.setReturnUrl("");
			//此处配前端页面
			//request.setNotifyUrl(Constant.ALI_NOTIFY_URL);
			request.setNotifyUrl(Constant.ALI_NOTIFY_URL_TEST);
			//request.setNotifyUrl("http://192.168.0.131:9999/member/pay/aliNotify");
			
			AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
			
			model.setOutTradeNo(outTradeNo);
			model.setTotalAmount(payTotal.toString());
			model.setSubject("快乐斑马后台商城订单");
			
			List<GoodsDetail> goodsDetailList = new ArrayList<>();
			
			GoodsDetail goodsDetail = new GoodsDetail();
			goodsDetail.setGoodsId(String.valueOf(System.currentTimeMillis()));
			goodsDetail.setGoodsName("购买套餐在线课纠错大师权限");
			goodsDetail.setQuantity(1L);
			goodsDetail.setPrice(payTotal.toString());
			goodsDetailList.add(goodsDetail);
			
			model.setGoodsDetail(goodsDetailList);
			
			SettleInfo settleInfo = new SettleInfo();
			
			List<SettleDetailInfo> settleDetailInfos = new ArrayList<>();
			SettleDetailInfo detailInfo = new SettleDetailInfo();
			
			detailInfo.setTransInType("loginName");
			detailInfo.setTransIn("cuijin@joymido.com");
			detailInfo.setAmount(payTotal.toString());
			
			settleDetailInfos.add(detailInfo);
			settleInfo.setSettleDetailInfos(settleDetailInfos);
			model.setSettleInfo(settleInfo);
			
			request.setBizModel(model);
			
			response = alipayClient.execute(request);
			
			if (response.isSuccess()) {
				log.info("调用成功");
				log.info(JSONObject.toJSONString(response));
			} else {
				log.error("调用失败");
				log.error(JSONObject.toJSONString(response));
			}
		} catch (AlipayApiException e) {
			log.error(e.getMessage(), e);
		}
		
		Map returnMap = new HashMap();
		returnMap.put("response", response);
		
		return returnMap;
	}

//	/**
//	 * 硬件支付押金
//	 *
//	 * @param map
//	 * @param request
//	 * @return java.util.Map<java.lang.String, java.lang.String>
//	 * @author nianhua.jiang
//	 * @date 2021/10/22 14:14
//	 */
//	@Override
//	public Map<String, Map> wxPayHardwareDeposit(Map<String, Object> map, HttpServletRequest request) {
//
//		//获取支付金额
//		Integer goodsId = (Integer) map.get("goodsId");
//		//姓名
//		String name = (String) map.get("name");
//		//手机号/联系方式 必填项，为了追述
//		String phone = (String) map.get("phone");
//		//邮寄地址
//		String address = (String) map.get("address");
//		//合作商（机构）ID
//		Integer orgId = (Integer) map.get("orgId");
//		//订单编号
//		String orderNo = (String) map.get("orderNo");
//
//		MemberOrder memberOrder = new MemberOrder();
//		//获取充值金额
//		BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(goodsId);
//		memberOrder.setOrderNo(Long.valueOf(orderNo));
//		//订单价格
//		memberOrder.setPrice(basicGoodsInfo.getGoodsPrice());
//		//机构ID
//		memberOrder.setOrgId(orgId);
//		//支付类型 9 -> 硬件押金
//		memberOrder.setOrderType("9");
//		//收货人
//		memberOrder.setExpressName(name);
//		//收货人联系电话
//		memberOrder.setExpressPhone(phone);
//		//收货人地址
//		memberOrder.setExpressAddress(address);
//		//商品ID
//		memberOrder.setGoodsId(goodsId);
//		//生成会员订单
//		createMemberOrder(memberOrder, Constant.PAY_WX);
//
//		try {
//			Map<String, Map> payResult = WXPay
//					.wxPrePay(basicGoodsInfo.getGoodsPrice().toString(), "纠错大师租赁押金", payNotifyProperties.getWxNotify(),
//							String.valueOf(memberOrder.getOrderNo()),
//							request);
//
//			return payResult;
//
//		} catch (NumberFormatException e) {
//			e.printStackTrace();
//			throw new BusinessException(e.getMessage());
//		}
//
//	}
	
	/**
	 * 硬件支付押金
	 *
	 * @param map
	 * @param request
	 * @return java.util.Map<java.lang.String, java.lang.String>
	 * @author nianhua.jiang
	 * @date 2021/10/22 14:14
	 */
	@Override
	public Map<String, String> wxPayHardwareDeposit(Map<String, Object> map, HttpServletRequest request) {
		
		//获取支付金额
		Integer goodsId = (Integer) map.get("goodsId");
		//姓名
		String name = (String) map.get("name");
		//手机号/联系方式 必填项，为了追述
		String phone = (String) map.get("phone");
		//邮寄地址
		String address = (String) map.get("address");
		//合作商（机构）ID
		Integer orgId = (Integer) map.get("orgId");
		//订单编号
		String orderNo = (String) map.get("orderNo");
		//身份证号
		String identityCardNo = (String) map.get("identityCardNo");
		
		MemberOrder memberOrder = new MemberOrder();
		//获取充值金额
		BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(goodsId);
		memberOrder.setOrderNo(Long.valueOf(orderNo));
		//订单价格
		memberOrder.setPrice(basicGoodsInfo.getGoodsPrice());
		//机构ID
		memberOrder.setOrgId(orgId);
		//支付类型 9 -> 硬件押金
		memberOrder.setOrderType("9");
		//收货人
		memberOrder.setExpressName(name);
		//收货人联系电话
		memberOrder.setExpressPhone(phone);
		//收货人地址
		memberOrder.setExpressAddress(address);
		//商品ID
		memberOrder.setGoodsId(goodsId);
		//身份证号
		memberOrder.setIdentityCardNo(identityCardNo);
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_WX);
		
		//调用微信统一下单接口
		SortedMap<Object, Object> parameters = new TreeMap<>();
		parameters.put("mch_id", WxConfigUtil.MCH_ID);
		parameters.put("appid", WxConfigUtil.APPID);
		parameters.put("nonce_str", PayCommonUtil.createNoncestr());
		parameters.put("body", "硬件租赁押金");
		parameters.put("out_trade_no", String.valueOf(memberOrder.getOrderNo()));
		int fen = memberOrder.getPrice().multiply(new BigDecimal(100)).intValue();
		String totalFee = String.valueOf(fen);
		parameters.put("total_fee", totalFee);
		parameters.put("spbill_create_ip", PayCommonUtil.getIPAddress());
		parameters.put("notify_url", payNotifyProperties.getWxNotify());
		parameters.put("trade_type", "MWEB");
		//场景信息
		Map<String, Object> sceneMap = new LinkedHashMap<String, Object>();
		Map<String, Object> h5Info = new LinkedHashMap<String, Object>();
		h5Info.put("type", "Wap");
		h5Info.put("wap_url", "https://depositlease.joymido.com/");
		h5Info.put("wap_name", "扫码支付");
		sceneMap.put("h5_info", h5Info);
		parameters.put("scene_info", JSON.toJSONString(sceneMap));
		Map<String, String> resMap = PayCommonUtil.wxRequest(WxConfigUtil.UNIFIED_ORDER_URL, "POST", WxConfigUtil.MD5, parameters);
		resMap.put("orderId", String.valueOf(memberOrder.getOrderNo()));
		//配置微信支付成功回调地址
		resMap.put("mweb_url", resMap.get("mweb_url") + "&redirect_url=https%3A%2F%2F" + "depositlease.joymido.com/" + "%23" + "/load/?flag=wx@" + String.valueOf(memberOrder.getOrderNo()) + "@");
		return resMap;
	}
	
	@Override
	public PayHardwareDepositResultVO getPayHardwareDepositResult(String orderNo) {
		
		//获取订单信息
		PayHardwareDepositResultVO resultVO = memberOrderMapper.getPayHardwareDepositResult(orderNo);
		//获取商品信息
		BasicGoodsInfo basicGoodsInfo = goodsInfoMapper.selectById(resultVO.getGoodsId());
		//商品名称
		resultVO.setOrderType(basicGoodsInfo.getName());
		//企业名称
		resultVO.setBusinessName("大连佳音科技有限公司");
		//企业联系电话
		resultVO.setBusinessPhone("400-0123-485");
		return resultVO;
	}
	
	/**
	 * 后台商城订单后续处理 如果购买套餐则新生成激活码, 若包含纠错条则后台自动生成新销售单
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	protected void postProcessMallOrder(MemberOrder memberOrder) throws Exception {
		Long orderNo = memberOrder.getOrderNo();
		
		//从数据库找出本次购买商品的详情
		List<MemberOrderDetail> orderDetailList = orderDetailMapper.selectList(new QueryWrapper<MemberOrderDetail>().eq("order_no", orderNo));
		
		//选取纠错大师权限
		List<BasicGoodsInfo> masterList = goodsInfoMapper.selectList(new QueryWrapper<BasicGoodsInfo>().like("name", "纠错大师"));
		//选取所有硬件
		List<GoodsInfoVO> deviceList = goodsInfoMapper.selectHardwareGoods(null);
		//选取在线课时长
		List<BasicGoodsInfo> onlineCourseTimeList = goodsInfoMapper.selectList(new QueryWrapper<BasicGoodsInfo>().like("name", "在线课"));
		
		OptOperator opt;
		OrgOrganization org;
		String contact = null;
		String address = null;
		Integer optId = memberOrder.getOptId();
		Integer orgId = memberOrder.getOrgId();
		
		if (optId == null && orgId == null) {
			throw new BusinessException("机构和运营商ID必须至少提供一个");
		}
		
		if (optId != null) {
			opt = operatorMapper.selectOne(new QueryWrapper<OptOperator>().eq("id", optId));
			if (opt == null) {
				throw new BusinessException("未找到运营商，请检查运营商相关信息");
			}
			contact = opt.getPhone() + " " + opt.getLeader();
			address = opt.getAddress();
		}
		if (orgId != null) {
			org = organizationMapper.selectOne(new QueryWrapper<OrgOrganization>().eq("id", orgId));
			if (org == null) {
				throw new BusinessException("未找到机构，请检查运营商相关信息");
			}
			contact = org.getPhone() + " " + org.getIdName();
			address = org.getAddress();
		}
		
		Map<Integer, Integer> goodsMap = new HashMap();
		
		for (MemberOrderDetail orderDetail : orderDetailList) {
			Integer comboId = orderDetail.getComboId();
			Integer goodsId = orderDetail.getGoodsId();
			Integer count = orderDetail.getComboCount() == null ? orderDetail.getGoodsCount() : orderDetail.getComboCount();
			
			//处理订单套餐部分
			if (comboId != null) {
				List<BasicComboGoods> mappingList = comboGoodsMapper.selectList(new QueryWrapper<BasicComboGoods>().eq("combo_id", comboId));
				
				for (BasicComboGoods mapping : mappingList) {
					doIfGoodsMatchMaster(mapping.getGoodsId(), masterList, deviceList, comboId, optId, orgId, count * mapping.getQuantity(), goodsMap);
					doIfGoodsMatchOnlineCourse(goodsId, onlineCourseTimeList, optId, orgId, count);
				}
			} else if (goodsId != null) {
				//处理订单商品部分(纠错大师权限，在线课时长)部分
				doIfGoodsMatchMaster(goodsId, masterList, deviceList, null, optId, orgId, count, goodsMap);
				doIfGoodsMatchOnlineCourse(goodsId, onlineCourseTimeList, optId, orgId, count);
			}
		}
		
		addSaleOrder(orderNo, contact, address, optId, orgId, goodsMap);
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	protected void doIfGoodsMatchMaster(Integer goodsId, List<BasicGoodsInfo> masterList, List<GoodsInfoVO> deviceList, Integer comboId, Integer optId, Integer orgId, Integer count, Map<Integer, Integer> goodsMap) throws Exception {
		//遍历纠错大师权限列表
		for (BasicGoodsInfo master : masterList) {
			if (goodsId == master.getId()) {
				//套餐内容匹配到对应纠错大师权限，则需生成激活码
				for (int i = 0; i < count; i++) {
					remoteOrgService.genCode(master.getUnitCount(), 1, "生成后台商城套餐激活码", comboId, optId, orgId);
				}
				
				return;
			}
		}
		
		//遍历硬件列表
		for (GoodsInfoVO goodsInfo : deviceList) {
			if (goodsId == goodsInfo.getId()) {
				//套餐内容匹配到纠错条, 则添加到新增销售单商品List
				if (goodsMap.containsKey(goodsId)) {
					goodsMap.put(goodsId, goodsMap.get(goodsId) + count);
				} else {
					goodsMap.put(goodsId, count);
				}
				
				break;
			}
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	protected void doIfGoodsMatchOnlineCourse(Integer goodsId, List<BasicGoodsInfo> onlineCourseTimeList, Integer optId, Integer orgId, Integer count) throws Exception {
		//遍历在线课时长列表
		for (BasicGoodsInfo onlineCourse : onlineCourseTimeList) {
			if (goodsId == onlineCourse.getId()) {
				if (orgId != null) {
					OrgOrganization orgEntity = organizationMapper.selectOne(new QueryWrapper<OrgOrganization>().eq("id", orgId));
					//增加在线课对应对应时长
					if (orgEntity != null) {
						Integer avail = orgEntity.getOnlineCourseAvail();
						orgEntity.setOnlineCourseAvail(avail == null ? 0 : avail + onlineCourse.getUnitCount() * count);
						organizationMapper.updateById(orgEntity);
					}
				} else if (optId != null) {
					OptOperator optEntity = operatorMapper.selectOne(new QueryWrapper<OptOperator>().eq("id", optId));
					//增加在线课对应对应时长
					if (optEntity != null) {
						Integer avail = optEntity.getOnlineCourseAvail();
						optEntity.setOnlineCourseAvail(avail == null ? 0 : avail + onlineCourse.getUnitCount() * count);
						operatorMapper.updateById(optEntity);
					}
				}
			}
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	protected void addSaleOrder(Long orderNo, String contact, String address, Integer optId, Integer orgId, Map<Integer, Integer> goodsMap) throws Exception {
		StockSaleOrderVO orderVO = new StockSaleOrderVO();
		
		if (optId != null) {
			orderVO.setOptId(optId);
		}
		if (orgId != null) {
			orderVO.setOrgId(orgId);
		}
		
		orderVO.setOrderNo(orderNo);
		orderVO.setContact(contact);
		orderVO.setAddress(address);
		orderVO.setOutStatus(ShoppingStockConstants.STATUS_NOT_OUT);
		orderVO.setCommitStatus(ShoppingStockConstants.ORDER_UNCOMMITED);
		//若是商城生成，则制单人些运营商或者机构ID
		orderVO.setCreatedBy(String.valueOf(orgId == null ? optId : orgId));
		orderVO.setCreateTime(LocalDateTime.now());
		
		//入库销售单
		R orderInsertResult = remoteOptService.addSaleOrder(orderVO);
		
		//一个套餐里一定只有一个永久纠错条
		//暂时只有永久纠错条
		for (Map.Entry goodsEntry : goodsMap.entrySet()) {
			StockSaleOrderDetailVO detailVO = new StockSaleOrderDetailVO();
			detailVO.setOrderNo(orderNo);
			Integer goodsId = (Integer) goodsEntry.getKey();
			detailVO.setGoodsId(goodsId);
			BasicGoodsInfo goodsInfo = goodsInfoMapper.selectOne(new QueryWrapper<BasicGoodsInfo>().eq("id", goodsId));
			detailVO.setQuantity((Integer) goodsEntry.getValue());
			String type = "0".equals(goodsInfo.getUseType()) ? ShoppingStockConstants.DEVICE_UNLIMITED : ShoppingStockConstants.DEVICE_RENT;
			detailVO.setType(type);
			
			//入库销售详情
			R orderDetailInsertResult = remoteOptService.addSaleOrderDetail(detailVO);
			
			continue;
		}
	}
	
	/**
	 * 校验激活码是否重复
	 *
	 * @param code
	 * @return boolean
	 * @author nianhua.jiang
	 * @date 2020/11/18 13:25
	 **/
	private Boolean haveRepeat(String code) {
		QueryWrapper queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("actv_code", code);
		if (memberActivateMapper.selectList(queryWrapper).size() > 0) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 新增IOS支付LOG
	 *
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2021/7/16 17:32
	 */
	@Override
	public Boolean addIosOrderLog(String orderId, String productId, String transactionId, String payload, String memberId) {
		
		IosPayLog iosPayLog = new IosPayLog();
		iosPayLog.setCreateTime(LocalDateTime.now());
		iosPayLog.setMemberId(memberId);
		iosPayLog.setPayload(payload);
		iosPayLog.setTransactionId(transactionId);
		iosPayLog.setProductId(productId);
		iosPayLog.setOrderId(orderId);
		return iosPayLogMapper.insert(iosPayLog) == 1;
		
	}
	
	/**
	 * 创建出货单
	 *
	 * @param orderNo 订单编号
	 * @param orgId   机构ID
	 * @param optId   运营商ID
	 * @param name    用户名称
	 * @param phone   手机号
	 * @author nianhua.jiang
	 * @date 2021/10/25 14:05
	 */
	private void createOutSaleOrder(Long orderNo, Integer orgId, Integer optId, String name, String phone, String address) {
		
		//新增出库单
		StockSaleOrder saleOrder = new StockSaleOrder();
		//状态
		saleOrder.setCommitStatus("1");
		//订单编号
		saleOrder.setOrderNo(orderNo);
		//客户 ID（机构）
		saleOrder.setOrgId(orgId);
		//客户 ID（运营商）
		saleOrder.setOptId(optId);
		//联系人
		saleOrder.setContact(phone + " " + name);
		//说明
		saleOrder.setComments("用户押金缴纳完成，等待机构缴纳服务费，暂不可发货");
		//不可发货
		saleOrder.setIsOut("0");
		//发货类型 1-销售出货 2-换货出货 3-合作商押金出库
		saleOrder.setOutType("3");
		//出库数量
		saleOrder.setOutAmount(1);
		//提单人
		saleOrder.setCreatedBy("sys");
		//订单创建时间
		saleOrder.setCreateTime(LocalDateTime.now());
		//订单提交时间
		saleOrder.setCommitTime(LocalDateTime.now());
		//在总部仓库发货
		saleOrder.setWarehouseId(8);
		//邮寄地址
		saleOrder.setAddress(address);
		
		optFeignService.addStockSaleOrder(saleOrder);
		
	}
	
	@SneakyThrows
	@Override
	public void aliAgreementSignNotify(HttpServletRequest request, AliReturnPayBean returnPay, HttpServletResponse response) {
		
		//获取商家自定义的协议号
		String externalAgreementNo = returnPay.getExternal_agreement_no();
		//查询协议号对应的协议信息，兼容处理，防止多重数据
		List<SmMemberAgreementSign> smMemberAgreementSigns = signMapper.selectList(new QueryWrapper<SmMemberAgreementSign>().eq(SmMemberAgreementSign.COL_EXTERNAL_AGREEMENT_NO, externalAgreementNo));
		
		//查询订单是否已经签约成功
		boolean queryRes = AliPayUtil.agreementQuery(returnPay.getAgreement_no());
		
		//记录用户已经签约此服务，需要更新状态为已签约
		String memberId = smMemberAgreementSigns.get(0).getMemberId();
		Member member = memberMapper.selectById(memberId);
		
		if (queryRes) {
			
			//签约成功
			for (SmMemberAgreementSign smMemberAgreementSign : smMemberAgreementSigns) {
				//成功
				smMemberAgreementSign.setStatus("1");
				smMemberAgreementSign.setAlipayLogonId(returnPay.getAlipay_logon_id());
				smMemberAgreementSign.setAgreementNo(returnPay.getAgreement_no());
				signMapper.updateById(smMemberAgreementSign);
			}
			System.out.println("签约回调成功！");
			member.setIsAgreementSign("1");
		} else {
			//签约失败
			for (SmMemberAgreementSign smMemberAgreementSign : smMemberAgreementSigns) {
				//失败
				smMemberAgreementSign.setStatus("2");
				smMemberAgreementSign.setAgreementNo(returnPay.getAgreement_no());
				signMapper.updateById(smMemberAgreementSign);
			}
			member.setIsAgreementSign("0");
		}
		memberMapper.updateById(member);
	}
	
	@Override
	public void iosNotify(String jwt) {
		
		// 解析IOS返回的数据
		DecodedJWT decodedJWT = JWT.decode(jwt);
		String payload = new String(java.util.Base64.getDecoder().decode(decodedJWT.getPayload()));
		String header = new String(java.util.Base64.getDecoder().decode(decodedJWT.getHeader()));
		JSONObject payloadJsonObject = JSONObject.parseObject(payload);
		String data = payloadJsonObject.getString("data");
		JSONObject dataJsonObject = JSONObject.parseObject(data);
		String signedTransactionInfo = dataJsonObject.getString("signedTransactionInfo");
		DecodedJWT signedTransactionInfoJWT = JWT.decode(signedTransactionInfo);
		String signedPayload = new String(java.util.Base64.getDecoder().decode(signedTransactionInfoJWT.getPayload()));
		System.out.println("signedPayload===>" + signedPayload);
		JSONObject signedPayloadJsonObject = JSONObject.parseObject(signedPayload);
		String expiresDate = signedPayloadJsonObject.getString("expiresDate");
		String originalTransactionId = signedPayloadJsonObject.getString("originalTransactionId");
		String transactionId = signedPayloadJsonObject.getString("transactionId");
		LocalDateTime localDateTime = Instant.ofEpochMilli(Long.valueOf(expiresDate)).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
		log.info("订单ID ==>" + transactionId + "  过期时间为 ===>" + localDateTime.toString());
		
		if (localDateTime.isBefore(LocalDateTime.now())) {
			log.error("用户已终止自动续费");
			return;
		}
		
		//获取用户 memberId
		List<IosPayLog> iosPayLogs = iosPayLogMapper.selectList(new QueryWrapper<IosPayLog>().eq(IosPayLog.COL_TRANSACTION_ID, originalTransactionId));
		
		if (iosPayLogs.size() == 0) {
			log.error("未找到续费订单，服务终止：" + originalTransactionId);
			return;
		}
		
		//判断第一次是否续费成功
		List<MemberOrder> memberOrders = memberOrderMapper.selectList(new QueryWrapper<MemberOrder>().eq("sequence_number", transactionId));
		
		if (memberOrders.size() > 0) {
			log.info("订单已支付");
			return;
		}
		
		IosPayLog iosPayLog = iosPayLogs.get(0);
		
		MemberOrder memberOrder = new MemberOrder();
		//获取VIP价格
		SmMemberPrice smMemberPrice = smMemberPriceMapper.selectOne(new QueryWrapper<SmMemberPrice>().eq(SmMemberPrice.COL_IOS_CODE, IosPayUtils.VIP_AUTO_PAY));
		//订单价格
		memberOrder.setPrice(smMemberPrice.getPriceNowRMB());
		//订单类型 2-VIP购买
		memberOrder.setOrderType("2");
		//IOS 订单ID
		memberOrder.setSequenceNumber(transactionId);
		//用户memberId
		memberOrder.setMemberId(iosPayLog.getMemberId());
		//生成会员订单
		createMemberOrder(memberOrder, Constant.PAY_IOS);
		
		// sm_member_money_log 中追加充值记录信息（相当于订单记录信息）
		MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
		//交易金额
		memberMoneyLog.setMoney(memberOrder.getPrice());
		//创建时间
		memberMoneyLog.setCreateTime(LocalDateTime.now());
		//充值虚拟币数量
		memberMoneyLog.setGold(0);
		//订单编号
		memberMoneyLog.setOrderId(String.valueOf(memberOrder.getOrderNo()));
		//支付方式
		memberMoneyLog.setPayMethod("IOS");
		//会员ID
		memberMoneyLog.setMemberId(memberOrder.getMemberId());
		//实付金额
		memberMoneyLog.setActualMoney(memberOrder.getPrice());
		//备注
		memberMoneyLog.setComment("购买VIP" + smMemberPrice.getBuyMonths() + "个月");
		//新增操作
		memberMoneyLogMapper.insert(memberMoneyLog);
		
		//充值会员
		MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>().eq("member_id", memberOrder.getMemberId()).and(x -> x.eq("role_code", Constant.VIP_MEMBER)));
		
		if (role != null) {
			
			//创建时间
			role.setCreateTime(LocalDateTime.now());
			
			//如果还没到期，那么从到期时间开始累加
			if (role.getEndTime().isAfter(LocalDateTime.now())) {
				role.setEndTime(role.getEndTime().plusMonths(smMemberPrice.getBuyMonths()));
			}
			//如果已经到期，那么从今天开始累加会员天数
			else {
				role.setStartTime(LocalDateTime.now());
				role.setEndTime(LocalDateTime.now().plusMonths(smMemberPrice.getBuyMonths()));
			}
			memberRoleMapper.updMemberRole(role);
		} else {
			//新增会员
			role = new MemberRole();
			//创建时间
			role.setCreateTime(LocalDateTime.now());
			//开始时间
			role.setStartTime(LocalDateTime.now());
			//结束时间
			role.setEndTime(LocalDateTime.now().plusMonths(smMemberPrice.getBuyMonths()));
			//会员
			role.setRoleCode(Constant.VIP_MEMBER);
			//用户ID
			role.setMemberId(memberOrder.getMemberId());
			memberRoleMapper.saveMemberRole(role);
		}
		
		//赠送打印次数
		Member member = memberMapper.selectById(memberOrder.getMemberId());
		member.setPrintAmountGive(smMemberPrice.getGivePrintCount());
		member.setIsAgreementSign("1");
		memberMapper.updateById(member);
		
	}
	
	@Override
	public boolean batchAliTradePay() {
		
		//查询用户记录表
		List<SmMemberAgreementSign> agreementSigns = signMapper.selectList(new QueryWrapper<SmMemberAgreementSign>().isNotNull("agreement_no").eq("status", "1").orderByDesc("create_time"));
		
		for (SmMemberAgreementSign agreementSign : agreementSigns) {
			
			//续费扣款逻辑
			LocalDate payTime = agreementSign.getNextPayTime();
			//前一天或者当天进行扣款
			if (payTime.equals(LocalDate.now()) || LocalDate.now().plusDays(1).equals(payTime)) {
				
				//可以扣款，开始创建订单
				List<SmMemberPrice> memberPrices = smMemberPriceMapper.selectList(new QueryWrapper<SmMemberPrice>().eq("ios_code", IosPayUtils.VIP_AUTO_PAY));
				
				SmMemberPrice memberPrice = memberPrices.get(0);
				
				MemberOrder memberOrder = new MemberOrder();
				//订单价格
				memberOrder.setPrice(memberPrice.getPriceNowRMB());
				//充值月份
				memberOrder.setBuyMonth(memberPrice.getBuyMonths());
				//支付类型 2->VIP支付
				memberOrder.setOrderType("2");
				//赠送打印次数
				memberOrder.setGivePrintCount(memberPrice.getGivePrintCount());
				//用户ID
				memberOrder.setMemberId(agreementSign.getMemberId());
				//zebra 协议单号
				memberOrder.setExternalAgreementNo(agreementSign.getExternalAgreementNo());
				createMemberOrder(memberOrder, Constant.PAY_ALI);
				//请求支付宝主动扣款接口进行扣款
				AliPayUtil.tradPaySign(payNotifyProperties.getAliNotify(), String.valueOf(memberOrder.getOrderNo()), "VIP自动续费服务", agreementSign.getAgreementNo(), memberPrice.getPriceNowRMB().toString());
				
			}
			
		}
		
		return true;
	}
	
	private Boolean settledOrder(OrgOrganization organization) {
		
		//获取此机构的推荐代理
		List<OptOrg> optOrgs = optOrgService.list(new QueryWrapper<OptOrg>().eq("org_id", organization.getId()));
		
		if (optOrgs != null && optOrgs.size() > 0) {
			//总部给代理商结算数量 + 1
			OrgSettledCount orgSettledCount = new OrgSettledCount();
			//结算订单数量
			orgSettledCount.setOrderSettledCount(1);
			//opt - 总部给代理商结算，org - 代理商给机构结算
			orgSettledCount.setType("opt");
			//运营商ID
			orgSettledCount.setOptId(optOrgs.get(0).getOptId());
			//备注
			orgSettledCount.setComment("使用预存款自动结算");
			
			optFeignService.settledOrder(orgSettledCount);
		}
		
		//代理商给机构结算数量 + 1
		OrgSettledCount orgSettledCount = new OrgSettledCount();
		//结算订单数量
		orgSettledCount.setOrderSettledCount(1);
		//opt - 总部给代理商结算，org - 代理商给机构结算
		orgSettledCount.setType("org");
		//运营商ID
		orgSettledCount.setOrgId(organization.getId());
		//备注
		orgSettledCount.setComment("使用预存款自动结算");
		//
		optFeignService.settledOrder(orgSettledCount);
		return true;
	}
	
	private Boolean settledOrderEqualsPhone(OrgOrganization organization) {
		//获取此机构的推荐代理
		List<OptOrg> optOrgs = optOrgService.list(new QueryWrapper<OptOrg>().eq("org_id", organization.getId()));
		if (optOrgs != null && optOrgs.size() > 0) {
			//获取运营商ID
			Integer optId = optOrgs.get(0).getOptId();
			R<OptOperator> optR = optFeignService.getOptById(optId);
			OptOperator optOperator = optR.getData();
			if (optOperator != null && optOperator.getPhone().equals(organization.getPhone())) {
				//总部给代理商结算数量 + 1
				OrgSettledCount orgSettledCount = new OrgSettledCount();
				//结算订单数量
				orgSettledCount.setOrderSettledCount(1);
				//opt - 总部给代理商结算，org - 代理商给机构结算
				orgSettledCount.setType("opt");
				//运营商ID
				orgSettledCount.setOptId(optOrgs.get(0).getOptId());
				//备注
				orgSettledCount.setComment("代理商自己的机构自动结算");
				optFeignService.settledOrder(orgSettledCount);
			}
		}
		return true;
	}
	
}
